I have had this problem many times now and I really wonder why this is happening.
Here is its latest occurrence:
public function updateBirthDate(Request $request)
{
try {
$request->validate([
'email' => 'required|email',
'birthDate' => 'required|date_format:Y-m-d',
]);
$user = User::where('email', $request->email)->first();
$user->profile()->update(['birth_date' => Carbon::parse($request->birthDate)->timestamp]);
return response_success([], __FUNCTION__, __('verification.user_data_updated'));
} catch (Exception $exception) {
Log::error(__FUNCTION__, compact('exception'));
return response_error(__FUNCTION__, $exception->getMessage());
}
}
The code above didn't change 'birth_date' in database when I sent the request through Postman.
But when I ran the line below in tinker, it changed 'birth_date' in database:
$user->profile()->update(['birth_date' => Carbon::parse('1990-01-01')->timestamp]);
I suppose this is a bug in this Laravel version.
I have noticed the reason when one of my methods with update didn't work but another one worked.
The following didn't work:
$user->update([
'confirmation_code' => random_int(100000, 999999),
'email' => $request->email,
]);
The following worked:
$user->update([
'mail_confirmation' => true
]);
I have missed a basic point.
The second one works because 'mail_confirmation'
field is in $fillable
array but first one doesn't work because 'confirmation_code'
isn't in $fillable
array.
Update is one of the mass assignment methods of Laravel Eloquent ORM Model. Others are fill and create: https://laravel.com/docs/10.x/eloquent#allowing-mass-assignment
So, all the fields must be in $fillable
array unless $guarded
array is set.