Warm tip: This article is reproduced from stackoverflow.com, please click
database laravel-5 php

PHP set empty field in database to value

发布于 2020-03-31 22:54:51

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; 
           } 
Questioner
novice
Viewed
51
Andrew Larsen 2020-01-31 19:22

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.