created_by=$user->id?$user->id"> Fix issue in Laravel-8 trying to read property "id" on null-PHP Chinese Network Q&A
Fix issue in Laravel-8 trying to read property "id" on null
P粉194919082
P粉194919082 2023-11-08 14:07:01
0
2
461

This error occurs when runningphp artisan migrate:fresh --seedThis 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$useris empty.

    P粉478188786

    The problem here is that$userhas a value ofnullandnulldoes not have any attributes.

    $userwill always benullwhereas your codeAuth::user()will benull. You did not have an authenticateduserduring the seeding process.

    If you want to assignUserto your$modeland you have seeded theUsertable, you can get aUser like this.

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

    If you don't want a specificuserthen 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
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!