My goal is set value if field is empty.
But get "Trying to get property of non-object" error.
last_day is empty field, how to assign value 1 ?
public function getPointsForExercises(){
$ls = Auth::user()->lessons()->get();
$last_day = Auth::user()->user_settings->last_day;
if (empty($user->user_settings->last_lesson)) {
$user->user_settings->last_lesson = 1;
}
First problem: $user
variable is not defined.
What you are trying to achieve can be done using the exists
function to make sure the relation exists, and then update the value using the update
function, like this:
public function getPointsForExercises() {
$ls = Auth::user()->lessons()->get();
$last_day = Auth::user()->user_settings->last_day;
if (Auth::user()->user_settings()->exists() && empty(Auth::user()->user_settings->last_lesson)) {
Auth::user()->user_settings()->update([
'last_lesson' => 1
]);
}
The code above is not ending the function nor is it using the variables $ls
and $last_day
as your code.
still line $last_day = Auth::user()->user_settings->last_day; getting error "Trying to get property of non-object"
If
user_settings
doesn't exist you will get an error yes. You are not checking if it exists. Could easily be solved in a one liner like this:$last_day = (Auth::user()->user_settings()->exists() ? Auth::user()->user_settings->last_day : 'default value if it doesnt exist');