0
votes

I have a VueJS route in my SPA application. I would like to apply a Laravel Middleware to a route (the auth middleware, in this case).

Actually, I have try this:

app.js

const router = new VueRouter({
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'home',
            component: require('./views/Home').default,
        },
        {
            path: '/hello',
            name: 'hello',
            component: require('./views/Hello').default,
        },
    ],
});

routes/web.php

Route::get('/hello', 'HomeController@home')->middleware('auth');
Route::get('/{any}', 'FrontendController@index')->where('any', '.*');

In this code, I have try to link the auth middleware to the route /hello, but it don't work. What is the best way to do that ?

Thanks.

1
How do you know it doesn't work? Your browser simply could be automatically sending the cookies Laravel needs to identify you for the auth:web middleware. You can tell if you inspect request()->user() inside your controller.amphetamachine
@amphetamachine I don't understand what you would say. I know that it doesn't work because I have test this code. When I navigate to "/hello", it doesn't redirect me to "/login" (like the middleware is supposed to do)user10485200
Try reversing the order of the route declarations; I think Laravel follows last-man-in strategy for routes, i.e. the last one declared applies for an ambiguous route. You could also try debugging using ./artisan route:list.amphetamachine
@amphetamachine Same problem.user10485200

1 Answers

0
votes

I have not worked with Laravel for about 6 years, but with Vue. I believe that this is because you never get into your Laravel route, since the Vue app is assembled, and it is therefore fully available in the browser.

It would be different if you loaded the component in the Vue router via lazy load.

component: () => import(/* webpackChunkName: "hello" */ './views/helo.vue')

I don't know exactly how that works with Laravel. I use the Vue CLI tool. Hope this could help you a little.