Reputation: 733
So i have a page where user could update his username,email,avatar however i'm having issue with auth()->user()
. when the user updates his username or email or avatar everything goes okay and it updates however if he tries to view the settings again after updating he will get the error trying to get property of non object however after i did dd(auth()->user())
it seems that auth()->user()
is null
and the only way to fix it is to manually logout and then change the settings again which becomes sort of repetitive . my code:
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>
Upvotes: 0
Views: 93
Reputation: 13259
This line
$request->session()->flush();
is clearing the session and all its data. Therefore, the user is logged out.
You can fix it like this
$old = $request->session()->get('username');
$request->session()->flush();
$request->session()->put('username',$request->username);
auth()->login($user);
Upvotes: 2