20

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 :(

2
  • Why don't you use OAuth2 for authentication and check if the user is authenticated on each request ? Commented Aug 27, 2018 at 17:11
  • 1
    I guess I could, but that's a little advanced for my purposes and takes learning. Commented Aug 29, 2018 at 18:21

4 Answers 4

20

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:

Sign up to request clarification or add additional context in comments.

9 Comments

Working good. For reference I had to use instead window.auth_user = {!! json_encode($auth_user) !!}; Also, had to insert the blade script before the Vue root master component (header not footer in my case)
But what if the client refresh his page? Then he will loose the state. Is there a solution for?
Sorry for late question. What if user was logged out, but dont refresh page? For example if session ends.
Is this secure? @JulianPaoloDayag
@MayankDudakiya I'm not sure what you meant by secure. Technically speaking, nothing is secure in the front-end side. This method only exposes the user via a global javascript variable to the rendered html output which you can then access inside your Vue application. As long as you don't include any sensitive information into the user object like password, card credentials, etc... then you're just going to be fine.
|
4

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
    }
});

Comments

2

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

Comments

1

I'm working with laravel 7+ and it doesn't need to send Auth::user() via controller Just call it from your laravel blade template file like below

your-template-name.blade.php

@if (Auth::check())
    <script>window.authUser={!! json_encode(Auth::user()); !!};</script>
@else
    <script>window.authUser=null;</script>
@endif

inside YourComponent.vue, store authUser like this:

<script>
    export default {
        data() {
            return {
                authUser: window.authUser
            }
        },

        created() {
            console.log(this.authUser);
        },

        methods: {
            yourMethodName() {
                console.log(this.authUser);
            }
        }
    }
<script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.