Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

Laravel set default value for creating model instances

David Carr

Laravel Framework PHP & MySQL Tutorials

    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';


    Laravel Modules Book by David Carr

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

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

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