更新文件中的错误 - 当没有会话

时间:2018-03-31 14:54:21

标签: php laravel

我有一个表单供用户编辑他的个人资料帐户。因此,对于每个字段,如果每个字段都有一个值,则显示该值:“value =”{{$ user-> name}}“。但有时会出现此错误:

Trying to get property of non-object

你知道如何纠正这个问题吗?

<form method="post" action="{{route('user.update')}}">
    {{csrf_field()}}
    <div>
        <label for="name">Name</label>
        <input type="text" value="{{$user->name}}" name="name" class="form-control" id="name">
    </div>
    <div>
        <label for="surname">Surname</label>
        <input type="text" value="{{$user->surname}}" name="surname" class="form-control" id="surname">
    </div>
    <!-- other fields -->
    <input type="submit" value="Update"/>
</form>

更新方法:

 public function updateGeneralInfo(Request $request){

        $this->validate($request, [
            'name' => 'required',
        ]);

        $user = Auth::user();
        $user->name = $request->name;
        ...
        $user->save();

        return redirect()->back();
    }

1 个答案:

答案 0 :(得分:2)

在您的控制器中,您可以在返回视图之前进行检查:

if(Auth::check()){
    //return view and other stuff
}
else {
    //redirect to login
}

在你的刀片中:

<form method="post" action="{{route('user.update')}}">
    {{csrf_field()}}
    <div>
        <label for="name">Name</label>
        <input type="text" value="{{auth()->user()->name}}" name="name" class="form-control" id="name">
    </div>
    <div>
        <label for="surname">Surname</label>
        <input type="text" value="{{auth()->user()->surname}}" name="surname" class="form-control" id="surname">
    </div>
    <!-- other fields -->
    <input type="submit" value="Update"/>
</form>