DEV Community

Cover image for Bullet-proofed routing with Laravel and Vue (Part 1)
Osita Chibuike
Osita Chibuike

Posted on

Bullet-proofed routing with Laravel and Vue (Part 1)

Introduction

Laravel and Vue are two really cool software tools I fancy and quite frankly I kinda think there's no better combo for these guys. In this post we are gonna have a look at the routing tricks we can implement to get the most of these guys.

Routing especially with Vue is long business, so this is going to be a two part post, so stick around.

The Routing Problem

I know, we might not want to admit it but with Vue and laravel running a show as an spa, we usually have a routing problem.

What exactly is this problem

Case Scene

So we have an application with the following routes

/resource/
/posts/
/posts/{slug}

let's assume these routes are served via the web routes in laravel (routes/web.php), no biggie,

But when we move the magic over to vue, using the vue router, it becomes a really messy beast to deal with, for an spa all routes would have to be prefixed with the hash bang for vue to handle their translation appropriately.

therefore
/resource/ becomes !#/resources
/posts/ becomes !#/posts
/posts/{slug} becomes ??, you guessed it, bam !#/posts/{slug}

For cool devs such as ourselves and the amazing users we hope to have, this is not cool.

Moment of Truth.

At this point you are probably really annoyed and just want to see the solution, so here we go.

Now, vue attempts to fix this using the history values on the Vue router

const router = new Router({
        routes: routes,
        base: '/',
        mode: 'history',
        history: true
    });
Enter fullscreen mode Exit fullscreen mode

Using the router settings, we can set the history value to true and have them use the normal route values when clicked from the the route link router-link component.

But this is only a partial fix, since when we request a route from the main external link this gives us a error since now its laravel routing that's handling the mix, and no longer a show run by vue routing, so how do we ensure this remains a vue business

Well, this is the magic piece

Route::get('/{vue_capture?}', function () {
   return view('inner');
})->where('vue_capture', '^(?!storage).*$'); 
Enter fullscreen mode Exit fullscreen mode

This route setup essentially means that all routes that follow the after the / are immediately sent back to the blade file that hosts the vue root element and main implementation, in this case that blade file is "inner" the regex on the function, captures all except routes looking to access the storage links.

Conclusion

With this vue handles the show, and all things routing runs with vue. In the next post we'll have a look at the process of using vuex to authenticate and automatically redirect to appropriate routes, and of course how to do it in a bullet-proofed manner.

Top comments (1)

Collapse
 
Sloan, the sloth mascot
Comment deleted