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:
CodePudding user response:
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 = \App\Models\User::where('id', 5)->first();
If you don't want a particular User
then you could do:
$model->created_by = \App\Models\User::inRandomOrder()->first();
CodePudding user response:
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.