DEV Community

Israel Ortuño
Israel Ortuño

Posted on

Using Vue Router in a Laravel subroute

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!

Top comments (6)

Collapse
 
devhammed profile image
Hammed Oyedele

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');
});
Collapse
 
israelortuno profile image
Israel Ortuño

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();
});
Collapse
 
devhammed profile image
Hammed Oyedele

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

Collapse
 
johandalabacka profile image
Johan Dahl

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

Collapse
 
israelortuno profile image
Israel Ortuño • Edited

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

Collapse
 
devhammed profile image
Hammed Oyedele

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.