2

I have a model

class Foo extends Model
{
    protected $fillable = [
        'name',
        'user_id'
    ];

}

I would like to set Auth::user()->id by default to user_id column. So I added:

class Foo extends Model
{
    protected $fillable = [
        'name',
        'user_id'
    ];

    public function setUserIdAttribute()
    {
        $this->attributes['user_id'] = Auth::user()->id;

    }
}

And from my controller I'm calling for Foo::create($data) without user_id key. But it doesn't work as expected. store() gives Integrity constraint violation because of user_id is missing. (User already logged in to achieve create page)

2 Answers 2

5

You provide an example where you used accessors.

https://laravel.com/docs/5.1/eloquent-mutators#accessors-and-mutators

From official doc:

The accessor will automatically be called by Eloquent when attempting to retrieve the value of first_name:

If you want to set default value for some attributes you need to use Observers.

<?php
// file app/models/Foo.php
namespace App\Models;

use App\Observers\FooObserver;

class Foo extends Model
{
    protected $fillable = [
        'name',
        'user_id'
    ];

    public static function boot() {
        parent::boot();
        parent::observe(new FooObserver);
    }
}

<?php
// file app/observers/FooObserver.php
namespace App\Observers;

use App\Models\Foo;

class FooObserver {

    public function creating(Foo $model) {
        $this->user_id = Auth::user()->id;
    }
}

About model observers in official doc: https://laravel.com/docs/5.0/eloquent#model-observers

Sign up to request clarification or add additional context in comments.

Comments

5

i cannot find official documentation about model-observers for Laravel 5.6. but you can still do it by this code

public static  function boot()
{
    parent::boot(); // TODO: Change the autogenerated stub
    // it will automatically add authenticate user to created_by column of selected model 
    static::creating(function ($model){
        $model->created_by = auth()->user()->id;
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.