Link to SPA routes (VueJs, React, Angular) with Laravel router

Dejan Blazeski
3 min readAug 4, 2020

--

When we have a Single Page Application, the routing is handled with the javascript framework router — meaning Laravel is not aware of the routes in the SPA. That’s not an issue by itself, but means when we want to link to our app deep links from our backend, we have to hardcode the links.

An example — we want to send an email with a link to the user profile. We do have the route registered in our VueJS router, but not in Laravel.

So we’d probably end up with some hardcoded url:

// our web.php// First, a link to our spa.blade.php file containing the SPA
Route::view('/app/{any_path?}', 'spa')->where('any_path', '(.*)');
// Where we need the link, in our controller, mail etc..
url("/app/profile/{$user->username}")

The link generated with url() will work just fine, but I prefer using named routes instead — they’re easier to use, and if the link changes — all links are updated automatically… making it harder for us to break things unintentionally.

So, let’s make Laravel aware of our SPA router links.

Our approach — we will add dummy routes in our web.php file, just so the router is aware they exist, but Laravel will never reach & serve them.

Update: There’s a git repo with the code here.

As you know, routes in Laravel have priority order vertically top-to-bottom. When a route on top, matches the url pattern, Laravel stops searching for other matches down the routes file and serves the first route matched.
Perfect for our use case.

First, lets look at our SpaController:

Our index method, serves the SPA code — then handled by our JSframework of choice.

Our nonexisting method, is meant to be a placeholder, should never be reached. If it’s reached, it means our SPA router didn’t handle the request properly.

Now, our web.php file:

What happens here:

The “any_path?” route, will catch all links prefixed with “app”. Meaning, any route we register beneath, will be registered with Laravel but never get reached. Bingo!

That’s the place where you want to add your SPA links and use them in Laravel.

In the example above, there are 2 links added. Here’s the before/after in the same scenario:

As you can see, we can now use named parameters and handle the links dynamically. Just add the links you need to be linked in the backend as routes, no need to add all your SPA links.

Another example for the `/about` page.

Hope this will make your dev life a bit easier, as it did mine :).

On an unrelated note, are your Macbook Pro animations lagging? You should try switching to the dedicated (more powerful) graphic card when on power — automate it with this app https://gum.co/mac-auto-gpu

--

--

Dejan Blazeski
Dejan Blazeski

Written by Dejan Blazeski

Founder binge.app. Curious dev. Laravel / Angular / VueJs / React Native / Docker. Love stand up shows.

Responses (1)