0
0
Laravelframework~5 mins

Route naming in Laravel

Choose your learning style9 modes available
Introduction

Route naming helps you give easy-to-remember names to your web routes. This makes it simple to create links and manage routes without typing full URLs.

When you want to generate URLs or redirects without hardcoding paths.
When you have many routes and want to organize them clearly.
When you want to change a route URL but keep the same name for links.
When you build navigation menus that link to different pages.
When you want to use route names in tests or controllers.
Syntax
Laravel
Route::get('/path', [Controller::class, 'method'])->name('route.name');
Use the ->name('your.route.name') method after defining the route.
Route names are usually dot-separated strings to group related routes.
Examples
This names the route 'home'. You can use route('home') to get its URL.
Laravel
Route::get('/home', [HomeController::class, 'index'])->name('home');
This names the POST route for creating a user as 'user.create'.
Laravel
Route::post('/user/create', [UserController::class, 'store'])->name('user.create');
This names a route with a parameter as 'products.show'. You can pass the id when generating URLs.
Laravel
Route::get('/products/{id}', [ProductController::class, 'show'])->name('products.show');
Sample Program

This example defines a route named 'page.about' for the '/about' URL. Then it shows how to get the URL by using the route name.

Laravel
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PageController;

Route::get('/about', [PageController::class, 'about'])->name('page.about');

// In a Blade view or controller, you can generate the URL:
$url = route('page.about');
echo $url;
OutputSuccess
Important Notes

Always use route names when generating URLs to avoid errors if URLs change.

Route names should be unique in your application.

You can group routes and prefix names using Route groups for better organization.

Summary

Route naming lets you assign simple names to routes for easy URL generation.

Use the ->name() method after defining a route.

Named routes help keep your code clean and flexible.