Fix issue in Laravel-8 trying to read property "id" on null
P粉194919082
P粉194919082 2023-11-08 14:07:01
0
2
578

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粉194919082
P粉194919082

reply all(2)
P粉786432579

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.

P粉478188786

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();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template