As the title states, I'm a little confused how I would tackle a method in my Vue Component with if/else statement based on if the user is logged in and authenticated with Laravel's Auth facade. I'm making various Axios requests which I need to allow/disallow based on if user logged in.
I have VUEX setup and was thinking that I can use local storage somehow to have a state for isLoggedin for example that works with Laravel. But I don't know if this is correct method, or secure and presumably Laravel is already storing it's authentication. So can I just access that direct in Vue?
Some unclean solutions here that I don't think are the best - https://laracasts.com/discuss/channels/vue/hide-button-if-user-is-logged-with-laravel-and-vuejs
I can not find any examples for this :(
use Illuminate\Support\Facades\Auth; if (Auth::check()) { // The user is logged in... }
Laravel includes built-in authentication and session services which are typically accessed via the Auth and Session facades. These features provide cookie-based authentication for requests that are initiated from web browsers. They provide methods that allow you to verify a user's credentials and authenticate the user.
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:
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With