Learn Laravel Routing Techniques for Next.js

February 16, 2023 · 4 min read

Understanding Laravel Routing Techniques
Laravel is our favorite backend framework because it's easy to use and reliable. A great thing about Laravel is how easy it is to set up routes, which makes it simple to handle requests from the front end of your app.
If you’re new to Laravel, here’s an easy example to show you how it works:
use Illuminate\Support\Facades\Route;
Route::get('/blog/{slug}', [BlogController::class, 'show'])->name('blog.show');Imagine you’ve established a route for your blog post, resulting in a URL like this:
/blog/this-is-my-first-post.
When we want to show a list of posts on the front end of our Laravel application, we can use Laravel’s route helper to get the full URL.
@foreach($posts as $post)
<a href="{{ route('blog.show', $post->slug) }}">
{{ $post->title }}
</a>
@endforeachWhen it’s time to show a bunch of blog posts on the front end of your Laravel app, the framework’s built-in route helper is super helpful. It easily gets the full URL for each post, talk about convenience!
What’s more, if you need to change a route, you just have to update it in one place. The front end will match the change by itself, showing how simple and clear Laravel’s routing system is.

Integrating Next.js for frontend
For our website, we’ve chosen Next.js as our framework and paired it with a Headless CMS for content management.
Next.js introduces us to the world of file-based routing, which we employ for our blog section, adopting the pattern blog/[slug].js.
Here, slug is a part of the route that can change. Using Next.js’s features like getStaticPaths and getStaticProps, we can easily show all our blog posts with this dynamic route. This method keeps everything neat and in order, and it also makes our app work better and grow more easily.
The routing problem
On our Blog Index page, there is a React component that lists all the blog posts.
import Heading from '@/components/Heading';
import Layout from '@/layout/Layout';
export default function BlogIndex({ posts }) {
return (
<Layout title="Blog">
<Heading>Blog</Heading>
<div className="container py-32">
<div className="flex flex-wrap">
{posts.map((blog, index) => {
return (
<Link key={index} href={`/blog/${blog.slug}`}>
{blog.title}
</Link>
);
})}
</div>
</div>
</Layout>
);
}To get the routing for a single blog post, we have to use template literals, as you can see here:
href={`/blog/${blog.slug}`}.
There are quite a few issues with this approach:
It’s not easily readable and prone to typing errors.
If we make a typo, we have to visit the route for Next.js to throw a 404 error.
If this route is used in multiple components, we’ll have to update all of those files if the route ever changes.
It looks pretty ugly ❌
Coming from a Laravel background, we want a simpler and cleaner approach, as we mentioned in the first example. Fortunately, there’s a way to do that with just a few lines of code.
First, we can set up a routes.js file in the root folder. We can define all our dynamic routes that the front end needs.
export const routes = {
'blog.index': {
path: '/blog',
},
'blog.show': {
path: '/blog/{slug}',
},
'case-studies.index': {
path: '/case-studies',
},
'case-studies.show': {
path: '/case-studies/{slug}',
},
'careers.index': {
path: '/careers',
},
'careers.show': {
path: '/careers/{slug}',
},
};Now that we have our routes.js file in place, we need a route helper that will take our route name and generate the appropriate URL along with the parameters. Have a look at the route.js helper file:
import { routes } from '../routes';
const route = (name, params = {}) => {
if (! routes[name]) {
throw new Error(
`Route ${name} not found. Make sure you have added it to the routes.js file.`
);
}
const url = routes[name];
if (!params) {
return url.path;
}
return Object.keys(params).reduce((path, key) => {
return path.replace(`{${key}}`, params[key]);
}, url.path);
};
export default route;Now with our route helper in place, look at the before and after when linking to blog posts:
import route from '@/utils/route';
const Before = ({ blog }) => (
<Link href={`/blog/${blog.slug}`}>
{blog.title}
</Link>
)
const After = ({ blog }) => (
<Link href={route('blog.show', { slug: blog.slug })}>
{blog.title}
</Link>
)We can make this simpler by destructuring the blog object. Here’s the final BlogIndex page with the new route helper:
import Heading from '@/components/Heading';
import Layout from '@/layout/Layout';
import route from '@/utils/route';
export default function BlogIndex({ posts }) {
return (
<Layout title="Blog">
<Heading>Blog</Heading>
<div className="container py-32">
<div className="flex flex-wrap">
{posts.map(({ title, slug }, index) => {
return (
<Link key={index} href={route('blog.show', { slug })}>
{title}
</Link>
);
})}
</div>
</div>
</Layout>
);
}Routing is easy with Laravel’s route helper. This helpful tool makes it clear how URLs and parameters are set up, so developers can quickly find the paths they need. If you need to change any routes, just update the routes.js file in the root directory. The route helper takes care of the rest, making sure changes show up all over the app without extra manual updates.
The route helper can handle multiple parameters too, showing how flexible it is for complex routing needs.
// routes.js
export const routes = {
'blog.tags': {
path: '/blog/{tags}/{slug}',
},
}
// In our Category Index
route('blog.tags', {
tags: 'react',
slug: 'hello-world-in-react'
})
/*
*
This will render the following url:
/blog/react/hello-world-in-react
*/Final reflections on Next.js and routing
Navigating the routes in Next.js might be tricky, but using a route helper can make it much easier. This tool makes linking to routes in your app more straightforward, quicker, and efficient. Use the route helper to simplify your routing approach, and you’ll see how it improves the upkeep and growth of your Next.js projects.

Bring Your Ideas to Life 🚀
If you need help with a Laravel project let’s get in touch.
Lucky Media is proud to be recognized as a leading Laravel Development Agency
Technologies

Stay up-to-date
Be updated with all news, products and tips we share!

