DEV Community

Aleson França
Aleson França

Posted on

Optimize Laravel Routes

Routes are the entry point of any web apps. In Laravel, they are easy to define and very powerful but it's also easy to create issues that slow down your app.

here are some simple and effective tips to improve your routes and keep your code clean.


Use php artisan route:cache in prod

This command compiles all your routes into one file, which loads much faster.

php artisan route:cache
Enter fullscreen mode Exit fullscreen mode

❗ Note: Only routes using controllers can be cached. Routes with inline Closure functions will be ignored.


Group routes by context

Don't put all routes in one file. Group them by domains or features.

Route::prefix('admin')->middleware('auth')->group(function () {
    Route::get('users', [AdminUserController::class, 'index']);
});
Enter fullscreen mode Exit fullscreen mode

Use single-action controllers

When a controller only has one method, using __invoke() keeps the code clean

Route::post('/contact', ContactFormController::class);
Enter fullscreen mode Exit fullscreen mode
class ContactFormController extends Controller
{
    public function __invoke(Request $request)
    {
        // your logic here
    }
}
Enter fullscreen mode Exit fullscreen mode

Name your routes

This avoids hardcoded URLs and makes updates easier

Route::get('/posts/{slug}', [PostController::class, 'show'])->name('posts.show');

// In Blade:
route('posts.show', ['slug' => $post->slug])
Enter fullscreen mode Exit fullscreen mode

Use middleware only when needed

Avoid adding global middleware if it’s only used in a few routes. This helps with performance and keeps things simpler.


Filter Route::resource with only or except

Only include the routes you really need:

Route::resource('posts', PostController::class)->only(['index', 'show']);
Enter fullscreen mode Exit fullscreen mode

Use route:list with filters to debug

php artisan route:list --path=api/posts --method=GET
Enter fullscreen mode Exit fullscreen mode

This helps find conflicts or mistakes with route names or middleware.


Conclusion

Optimizing routes is not just about performance it also helps with clean code, easier maintenance, and scalability. Laravel gives you the tools, so make the most of them!

Top comments (0)