search

Home  >  Q&A  >  body text

Fix issue in Laravel-8 trying to read property "id" on null

This error occurs when running php artisan migrate:fresh --seed This command will create a table in the MySQL database and populate the .env file with database details DB_DATABASE.

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:


P粉194919082P粉194919082401 days ago588

reply all(2)I'll reply

  • P粉786432579

    P粉7864325792023-11-09 13:01:31

    Change this line:

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

    Regarding:

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

    You must first check if $user is empty.

    reply
    0
  • P粉478188786

    P粉4781887862023-11-09 09:28:03

    The problem here is that $user has a value of null and null does not have any attributes.

    $user will always be null whereas your code Auth::user() will be null . You did not have an authenticated user during the seeding process.

    If you want to assign User to your $model and you have seeded the User table, you can get a User like this.

    $model->created_by = \App\Models\User::where('id', 5)->first();

    If you don't want a specific user then you can do this:

    $model->created_by = \App\Models\User::inRandomOrder()->first();

    reply
    0
  • Cancelreply