How to check in a Vue component if a user is authenticated in Laravel?
Usually from your controller, you pass the authenticated user object into the view which will then be stored in a javascript variable
Controller:
public function index(){ return view('index', [ 'auth_user' => Auth::user() ]);}
You will know if a user is authenticated if it returns an object or null where null means no user is authenticated.
In your blade, assign the auth_user
into a javascript variable:
<script> window.auth_user = {!! json_encode($auth_user); !!};</script>
your vuex store object should atleast look like this:
{ state: { user: null }, mutations: { setAuthUser(state, user) { state.user = user; } }, getters: { isLoggedIn(state) { return state.user !== null; } }}
Then in your Vue root component, get the auth_user
and save it into the store:
<script> export default { mounted() { this.$store.commit('setAuthUser', window.auth_user); } }</script>
You now basically have a getter
called this.$store.getters.isLoggedIn
that you can use in your application for checking if a user is currently logged in.
e.g:
Putting a script within blade file will throw Vue Warning. Let me answer "How to check in a Vue component if a user is authenticated in Laravel" and leave you with your Vuex complexity. Also this method is simpler.
So, in your controller:
public function index(){ return view('index')->with('auth_user', auth()->user());}
In your blade(main.blade.php):
<div class="container"> <example-component :auth_user='@json($auth_user)'></example-component></div>
In your vue-component, get your props(ExampleComponent.vue):
<script>export default { props: ['auth_user'], created () { console.log(this.auth_user) }}</script>
Returns null if user is not logged in
Use axios interceptors. You intercept the access denied http response code and then act accordingly.
window.axios.interceptors.response.use(function (response) { return response;}, function (error) { if (419 === error.response.status) { location.reload(); } else { //Something else you want to do or do nothing }});