Search code examples
laraveleloquentmodel

Laravel 9 - Set default model attribute to auth user id


I want to pass current user's id into a column by default. I tried giving it in the migration but didn't work, this code did work when I pass an integer but it gives an error when I try to set it to Auth::id()

Code I've tried (in the model file)

    protected $attributes = [
        'employee_id' => Auth::id(),
    ];

Error I get :

Constant expression contains invalid operations

It does work when I give it a hard coded string or integer value. But I need to give it the current user's id.


Solution

  • Not sure if it's really a good idea, but you can add this in your Model

    protected static function booted()
        {
            static::creating(function ($model) {
                $model->employee_id = Auth::id();
            });
        }
    

    Check the docs for the complete list of event.

    https://laravel.com/docs/9.x/eloquent#events-using-closures