Laravel Framework | PHP & MySQL | Tutorials

David Carr

Laravel set default value for creating model instances

Often when creating records with the ORM you'll set the same keys every time, in this cases you can take advantage of the creating event.

For example, imagine you have a Post model and where you store the logged in user id using the auth helper like this:

$post = new Post();
$post->title = 'Sample Title';
$post->user_id = auth()->id();

We can automate setting the user_id from within the model. Create a static boot method, call parent::boot() to bring in the parent's boot properties.

Next call static::creating it accepts a closure and will auto inject a queryBuilder instance. This allows you to set a column you want to save: 

protected static function boot()

    static::creating(function ($query) {
        $query->user_id = auth()->id();

Now when creating a new Post the user_id can be omited.

$post = new Post();
$post->title = 'Sample Title';


Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.