php - auth()->user() returns null after updating user -
so have page user update username,email,avatar i'm having issue auth()->user()
. when user updates username or email or avatar goes okay , updates if tries view settings again after updating error trying property of non object after did dd(auth()->user())
seems auth()->user()
null
, way fix manually logout , change settings again becomes sort of repetitive . code:
public function edit(request $request) { $user = auth()->user(); //if user did change 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 trying update 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 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() $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>
this line
$request->session()->flush();
is clearing session , data. therefore, user logged out.
you can fix this
$old = $request->session()->get('username'); $request->session()->flush(); $request->session()->put('username',$request->username); auth()->login($user);
Comments
Post a Comment