skip to Main Content

I got this error while running
php artisan migrate:fresh --seed
this command will create table in MySQL database and fill the database details DB_DATABASE in .env file.

    parent::boot();
    static::creating(function($model)
    {
    $user = Auth::user();
    model->created_by = $user->id ? $user->id : 1 ;
      });
      static::updating(function($model)
      {
       $user = Auth::user();```


Controller:

2

Answers


  1. The issue here is that the value of $user is null and null doesn’t have any properties.

    $user will always be null with your code as Auth::user() will be null. You have no authenticated User during the execution of your seeder.

    If you want to assign a User to your $model and you have seeded your User table, you could get a User that way.

    $model->created_by = AppModelsUser::where('id', 5)->first();
    

    If you don’t want a particular User then you could do:

    $model->created_by = AppModelsUser::inRandomOrder()->first();
    
    Login or Signup to reply.
  2. Change this line:

    model->created_by = $user->id ? $user->id : 1 ;
    

    to this:

    model->created_by = $user ? $user->id : 1 ;
    

    You must first check if the $user is empty or not.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search