拉拉维尔消息:更新时从空值创建默认对象

这是我的路线:


// Edit User Infos

Route::put('/edit/subscriber', 'Admin\UserController@editSubscriber')->name('/edit/subscriber');

公小号呼叫:


axios.put('/admin/edit/subscriber', {

                        userId: this.userDetails._id,

                        newFirstName: this.tempValueFirstName,

                        newLastName: this.tempValueLastName,

                        newPhone: this.tempValuePhone,

                        newEmail: this.tempValueEmail

                    }).then(({res}) => {

                        console.log(res)

                    }).catch(({err}) => {

                        console.log(err)

                    });

控制器中的更新功能:


public function editSubscriber() {

    $validated = request()->validate([

        'userId' => 'required',

        'newFirstName' => 'required|string|max:255',

        'newLastName' => 'required|string|max:255',

        'newEmail' => 'required|string|email|max:255',

        'newPhone' => 'nullable'

    ]);


    $user = User::find($validated['userId']);

    $user->first_name = $validated['newFirstName'];

    $user->last_name = $validated['newLastName'];

    $user->email = $validated['newEmail'];

    $user->phones = $validated['newPhone'];

    $user->name = $validated['newLastName'] . ' ' . $validated['newFirstName'];

    $user->save();

}

当我尝试使用我的更新功能时,更改像我想要的那样更新,但我得到这个500错误:“从空值创建默认对象”。


有人有想法吗?谢谢。


慕姐4208626
浏览 85回答 1
1回答

子衿沉夜

由于您的$user未正确初始化。确保您获得要更新的记录。并在值初始化后始终写下您在代码中使用的变量并正确条件。还要始终使用 try catch 语句来快速调试您的问题。可能下面的代码将对您有所帮助。 try {         $validated = request()->validate([                'userId' => 'required',                'newFirstName' => 'required|string|max:255',                'newLastName' => 'required|string|max:255',                'newEmail' => 'required|string|email|max:255',                'newPhone' => 'nullable'            ]);        if ($validated->fails()) {            return response($validated);        }else{           if (!blank($user)) {                $user = User::find($validated['userId']);                $user->first_name = $validated['newFirstName'];                $user->last_name = $validated['newLastName'];                $user->email = $validated['newEmail'];                $user->phones = $validated['newPhone'];                $user->name = $validated['newLastName'] . ' ' . $validated['newFirstName'];                $user->save();            }else{                //throw error response.            }        }    } catch (\Exception $ex) {        return response(ExceptionMessage($ex));    }
打开App,查看更多内容
随时随地看视频慕课网APP