0

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; 
           } 
novice
  • 321
  • 4
  • 19

2 Answers2

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.

Andrew Larsen
  • 1,197
  • 8
  • 19
  • still line $last_day = Auth::user()->user_settings->last_day; getting error "Trying to get property of non-object" – novice Jan 31 '20 at 11:32
  • 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');` – Andrew Larsen Jan 31 '20 at 12:02
0

You did not set the $user object.

firstly you have to make object :

$user = Auth::user()