Massassignmentexception in Model.php line 444: users_id

Asked

Viewed 46 times

0

I’m making a listerner to save when the user logs in, and prints the title error in User models.

public function accesses()
    {
        // Não esqueça de usar a classe Access: use App\Models\Access;
        return $this->hasMany(Access::class);
    }

public function registerAccess()
    {
        // Cadastra na tabela accesses um novo registro com as informações do usuário logado + data e hora
        return $this->accesses()->create([
            'user_id'   => $this->id,
            'datetime'  => date('Y-m-d H:i:s')
        ]);
    }

1 answer

1

Mistakes of MassAssignment usually occur because the entered field is not in the property $fillable of Model or is protected by the property $guarded of Model.

In your case you need to check whether user_id and datetime are as fillable in the model Access. Or else use the method relationship->save() to create the record.

Example using save():

public function registerAccess()
{
    return $this->accesses()->save(new Access([
        'user_id'   => $this->id,
        'datetime'  => date('Y-m-d H:i:s')
    ]);
}
  • added in this way, protected $fillable = [ 'name', 'email', 'password', 'user_id', 'datetime' ]; @fernandosavio o model->save() replaces create()?

  • In the model Access::class ?

  • 1

    create is used for mass assignment, such as adding an array of arrays with multiple Access to be created. save is used to save a single model. So create requires the model to know which fields are allowed to be entered in batch. That’s why save doesn’t check the field $fillable

  • changed to Return $this->hasMany('App Access'); remains the same.

  • tested with save too, error continues.

  • 1

    There is a detail that is bothering me. Exception says that the error is because of a field users_id but the question is user_id.&#Czech if you don’t have one typo in your class.

  • I got this fillable belongs to the Access model, not the users. Thanks @fernandosavio now I have another error to deal with. it’s rule he put the updated_at, created_at` no Insert?

  • 1

    If you change the value of the property $timestamps in your model Access he doesn’t do that. Look here at Docs

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.