Hi, my name is David Carr and I'm a PHP Developer.


Blog Archives Categories Authors About Me Open Source Books Contact Me

Sponsor Me

Help support the blog so that I can continue creating new content!

My Latest Book

Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Laravel set default value for creating model instances

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

 

Copyright © 2009 - 2022 David Carr. All code MIT license. All rights reserved.