Tutorials, PHP & MySQL, Laravel Framework

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

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.