0

i'm new in SPA and frontend frameworks too and i've got a problem to save state of logged in

for test i'm wrote a login and register form with vue and all gonna be ok with register and login(i've receive a user data by using the Auth::attempt) but when i restart a page i lost status of logged in during send a request again

but for the same time when i do it by blade on restart my logged state not change

this my method in UserController for API

public function api_login(Request $req){

        if (Auth::attempt(['email' => $req->email,'password' => hash('md5', $req->password)])){
            return response()->json(Auth::user());
        } else {
            return response()->json('no user found');
        }
    }

as far as i understand i miss something on response but google not find anything about it cause it silly question

12
  • Which Auth are you using, is it token based Sanctum? If so you can store the token in session storage, then have your front-end SPA (This would probably be a framework like Vue, React, Svelte or Angular) access and store the token for use with your API. I have a feeling you may not be doing an SPA if you are using blade files
    – Siimm Kahn
    Aug 22 at 10:47
  • use token based authentication, sanctum or passport authentication for apis
    – Akshay ak
    Aug 22 at 10:53
  • about blade say for example, im not using anything laravel package like sanctum,passport etc. when i need to login on laravel blade it can be easy get by auth::attempt and next request to app stay logged in, but in vue it some different
    – Andrew
    Aug 22 at 10:55
  • dont know how to do it
    – Andrew
    Aug 22 at 10:55
  • Yeah I don't think blade is going to work easily as an SPA with Vue. I would use Sanctum Token based Auth (Can upgrade to JWT down the line), then have a Vue App, use axios library to call the Laravel REST API routes, which will talk to your controller methods.
    – Siimm Kahn
    Aug 22 at 10:59

1 Answer 1

1

Yeah I don't think blade is going to work easily as an SPA with Vue (Somebody correct me if I'm wrong here). I would use Sanctum Token based Auth (Can upgrade to JWT down the line), then have a Vue App, use axios library to call the Laravel REST API routes, which will talk to your controller methods. You can then have your Vue functions inside a state library like Pinia and can store user and tokens in session storage (You should google where else you can store these tokens, as there are different debated options with pros/cons)

Using Vue Router Library you can check if token exists and if it doesn't send them back to login page. The token if exists can be used in your API calls, which should exists inside your callable Pinia State Libraries (you may need to read up on this).

This example is in Pinia State, but you can use Vuex as a state library. Then have a look at Vue Router, you will need to check required Auth, I will leave an example below.

 async login(email, pwd) {
        try {
            const user = await axios.post(`${apiUrl}login`, { email: email, password: pwd })
            if (user.data.success) {
                sessionStorage.setItem('TOKEN', user.data.result.token);
                sessionStorage.setItem('USER', JSON.stringify(user));
                this.header = { "Content-Type": "application/json", "Accept": "application/json", "Authorization": `Bearer ${user.data.result.token}` },
                this.token = user.data.result.token
                router.push('/Dashboard')
            } else {
                this.apiErrorMsg = user.data.message;
            }
        } catch (error) {
            console.log(error)
        }
    }

Router Example

const routes = [
{
    path: '/',
    // redirect: '/dashboard',
    component: DefaultLayout,
    meta: {requiresAuth: true},
    children: [
        {path: '/dashboard', name: 'Dashboard', component: Dashboard},
    ]
},
{
    path: '/login',
    redirect: '/login',
    name: 'Auth',
    component: Login,
    meta: {isGuest: true},
    children: [
        {path: '/login', name: 'Login', component: Login},
    ]
}
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

router.beforeEach((to, from, next) => {
    if (to.meta.requiresAuth && !sessionStorage.getItem('TOKEN')) {
        next({name: 'Login'})
    } else if (sessionStorage.getItem('TOKEN') && to.meta.isGuest) {
        next({name: 'Dashboard'});
    } else {
        next();
    }
})

export default router

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.