Using Vue Router in a Laravel subroute

github logo ・1 min read

I recently had to embed a Vue.js SPA into a Laravel application. As you may already know, your Apache/NGINX require some configuration in order to let the Vue Router handle the request rather than the default Laravel app.

For this particular case I could not make any change in the server side, so ended up with a quite elegant solution right into the Laravel router:

Route::get('/admin/{opt?}', function () {
 return view('your.index');
})->where('opt', '.*');

// or

Route::view('admin/{opt?}', 'your.index')->where('opt', '.*');

In this case I am using a /admin path but it should work too if you use /.

I hope it helps someone!

twitter logo DISCUSS (6)
markdown guide

There is a fallback method in Laravel router that calls the function you defined instead of showing 404 error so I think that is best, you can then handle 404 in your Frontend router.

// routes/web.php

| Web Routes
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!

Route::fallback(function () {
    return view('app');

This works perfect for / but if I was not able to make it work if your route is nested:

$router->group(['prefix' => 'admin'], function($router) {
    // $router->fallback('AdminController@index'); // This does not for '/'

    $router->get('/{opt?}', 'AdminController@index') // This one does
        ->where('opt', '.*')->fallback();

Yeah...perfect for a case where most of your views are rendered by a Frontend library like React, Vue is only available in root route group, does not work in nested groups.


Nice. I will try this tomorrow. Have been using vue-router with hashes in my project so far.


That's definitely an option! Didn't know about this one 👍


Yeah, I just add that to routes/web.php and all requests will be directed to my Frontend Router. With this, you can add other routes above and Laravel will only let the frontend handle the route when it does not recognize it.

Classic DEV Post from Nov 12

Feeling excluded and sad for not getting positive feedback - How should I react?

Israel Ortuño profile image

👋 Hey reader.

Do you prefer sans serif over serif?

You can change your font preferences in the "misc" section of your settings. ❤️