php - Using Laravel passport and Vuejs. Auth::User() doesn't work on blade
Get the solution ↓↓↓I am using Laravel 8 passport to authenticate users. From my Vuex store. I dispatch the login action like this:
login({ commit}, user) {
return new Promise((resolve, reject) => {
let url = `/auth/login`;
let email = user.email;
let password = user.password;
axios.post(url, { email, password })
.then(response => {
const token = response.data.token
const user = response.data.user
localStorage.setItem('AnimeStock.jwt', 'Bearer '+ token);
localStorage.setItem('AnimeStock.user', JSON.stringify(user));
axios.defaults.headers.common['Authorization'] = 'Bearer '+ token;
commit('AUTH_SUCCESS', {token, user});
resolve(response);
})
.catch(error => {
console.log(error)
commit('AUTH_ERROR', error.response.data.error)
localStorage.removeItem('AnimeStock.jwt')
localStorage.removeItem('AnimeStock.user')
reject(error)
})
})
}
This works and the user is authenticated. Next, I try to fetch the user from my vue component like this.
api.get(`/auth/user`).then(response => {
console.log(response.data)
});
My API route:
Route::group(['prefix' => 'auth'], function () {
//Auth routes
Route::post('login', 'AuthController@login');
Route::post('register', 'AuthController@register');
Route::group(['middleware' => 'auth:api'], function() {
Route::get('logout', 'AuthController@logout');
Route::get('user', 'AuthController@user');
});
});
It hits my AuthController and returns the current logged in user.
public function user()
{
$user = Auth::user();
return response()->json($user);
}
Here's the problem, when I do this on my layout blade file, it doesn't work:
<script>
@auth
window.User= {!! json_encode(Auth::user(), true) !!};
@else
window.User= [];
@endauth
</script>
This doesn't work either
<script>
@if(Auth::check())
window.User= {!! json_encode(Auth::user(), true) !!};
@else
window.User= [];
@endif
</script>
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.