auth() - > user()在更新用户

时间:2017-04-07 15:14:54

标签: php laravel

所以我有一个页面,用户可以更新他的用户名,电子邮件,头像,但我遇到auth()->user()的问题。当用户更新他的用户名或电子邮件或头像时一切正常并且更新但是如果他在更新后尝试再次查看设置,他将获得错误尝试获取非对象的属性但是在我做dd(auth()->user())后似乎auth()->user()null,解决问题的唯一方法是手动注销,然后再次更改设置,这会变得有点重复。我的代码:

public function edit(Request $request)
{
    $user = auth()->user();
    //If user did change his username or email or both.
    if(!$request->username === $user->username || !$request->email === $user->email)
    {
        $this->validate($request,[
           'username' => 'min:1|unique:users',
           'email' => 'min:1|unique:users|email',
           'avatar' => 'mimes:jpeg,jpg,gif,png'
        ]);
    }
    //Check if user is trying to update his avatar
    if($request->file('avatar'))
    {
        $image = $request->file('avatar');
        $image->store('avatars','s3');
        $name = $image->hashName();
        $src = "https://d1nm0o13p1ms88.cloudfront.net/avatars/$name";
        $user->avatar($src);
    }
    $user->username = $request->username;
    $user->email = $request->email;
    $user->save();
    $old = $request->session()->get('username');
    $request->session()->flush();
    $request->session()->put('username',$request->username);
}

settings.blade.php

{{--this returns the session--}}
{{dd(Session::get('username'))}}
{{--this returns null--}}
{{dd(auth()->user())}}
<div class="settings">
<div class="ui top attached tabular menu">
    <a class="active item">Tab</a>
</div>
<div class="ui bottom attached active tab segment">
    @if (count($errors) > 0)
        <div class="ui error message">
            @foreach ($errors->all() as $error)
            <p>{{$error}}</p>
            @endforeach
        </div>
    @endif
    <form method="POST" action="/settings" enctype="multipart/form-data">
        {{csrf_field()}}
    <div class="ui form">
        <div class="field">
            <label>Username:</label>
            <input type="text" name="username" value="{{auth()->user()->username}}">
        </div>
    </div>
        <div class="ui form" style="margin-top: 20px;">
            <div class="field">
                <label>Email:</label>
                <input type="text" name="email" value="{{auth()->user()->email}}">
            </div>
        </div>
        <div class="ui form" style="margin-top: 20px;">
            <div class="field">
                <label>Avatar:</label>
                <img src="{{auth()->user()->avatar}}" style="width:180px; height:180px;"> <br>
                <input type="file" name="avatar">
            </div>
        </div>
        <input class="ui button" type="submit" value="Save" style="margin-top: 30px;">
    </form>
</div>
</div>

1 个答案:

答案 0 :(得分:2)

这一行

$request->session()->flush();

正在清除会话及其所有数据。因此,用户已注销。

您可以像这样修复

$old = $request->session()->get('username');
$request->session()->flush();
$request->session()->put('username',$request->username);
auth()->login($user);