How to check in a Vue component if a user is authenticated in Laravel?

前端 未结 4 1732
醉酒成梦
醉酒成梦 2021-02-04 07:49

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 Larav

4条回答
  •  走了就别回头了
    2021-02-04 08:36

    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:

    
    

    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:

    
    

    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:

提交回复
热议问题