Loading...

Laravel set default value for creating model instances

David Carr

1 min read - 8th Feb, 2018

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();
$post->save();

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()
{
    parent::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';
$post->save();

 

0 comments
Add a comment