Laravel - Routing
Laravel - Routing
Section titled “Laravel - Routing”Introduction
Section titled “Introduction”The most basic Laravel routes simply accept a URI and a Closure, providing a very simple and expressive method of defining routes:
Basic Routing
Section titled “Basic Routing”All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group.
For most applications, you will begin by defining routes in your routes/web.php file.
The default routes/web.php file might look like this:
use Illuminate\Support\Facades\Route;
Route::get('/', function () { return view('welcome');});This route defines that for a GET request to the root URL (/), Laravel should execute the provided closure. This closure returns the welcome view, which typically corresponds to resources/views/welcome.blade.php.
Available Router Methods
Section titled “Available Router Methods”The router allows you to register routes that respond to any HTTP verb:
Route::get($uri, $callback);Route::post($uri, $callback);Route::put($uri, $callback);Route::patch($uri, $callback);Route::delete($uri, $callback);Route::options($uri, $callback);Sometimes you may need to register a route that responds to multiple HTTP verbs. You may do so using the match method. Or, you may even register a route that responds to all HTTP verbs using the any method:
Route::match(['get', 'post'], '/', function () { //});
Route::any('/', function () { //});The Routing Mechanism for the Welcome Page
Section titled “The Routing Mechanism for the Welcome Page”The process for displaying Laravel’s default welcome page involves these steps:
- Step 1: A user navigates to the root URL of your application (e.g.,
http://localhost:8000/). - Step 2: Laravel’s router checks the
routes/web.phpfile for a matching route. It findsRoute::get('/', ...);. - Step 3: The closure associated with this route is executed:
function () { return view('welcome'); }. - Step 4: The
view('welcome')function tells Laravel to render the Blade template located atresources/views/welcome.blade.php. - Step 5: Laravel processes this Blade file, compiles it into plain PHP, and then into HTML, which is sent back to the user’s browser.
- Step 6: The browser displays the default Laravel welcome page, often showing ‘Laravel’ in large text in the center.
CSRF Protection
Section titled “CSRF Protection”Any HTML forms pointing to POST, PUT, PATCH, or DELETE routes that are defined in the web routes file should include a CSRF token field. Otherwise, the request will be rejected. You can read more about CSRF protection in the CSRF documentation.
<form method="POST" action="/profile"> @csrf ...</form>Route Parameters
Section titled “Route Parameters”Sometimes you will need to capture segments of the URI within your route. For example, you may need to capture a user’s ID from the URL. You may do so by defining route parameters:
Required Parameters
Section titled “Required Parameters”Route parameters are always encased within {} braces and should consist of alphabetic characters. Route parameters are injected into route callbacks / controllers based on their order.
Route::get('/user/{id}', function ($id) { return 'User ID: ' . $id;});If you visit http://localhost:8000/user/5, the output will be ‘User ID: 5’. The value 5 is captured from the URL and passed as $id to the closure.
Optional Parameters
Section titled “Optional Parameters”Occasionally you may need to specify a route parameter that may not always be present in the URI. You may do so by placing a ? mark after the parameter name. Make sure to give the route’s corresponding variable a default value:
Route::get('/user/{name?}', function ($name = null) { return 'Username: ' . ($name ?? 'Guest');});
Route::get('/posts/{post}/comments/{comment?}', function ($postId, $commentId = null) { if ($commentId) { return "Viewing comment {$commentId} for post {$postId}."; } return "Viewing all comments for post {$postId}.";});Example of Route Parameters
Section titled “Example of Route Parameters”Let’s update routes/web.php with a few examples:
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
// Default welcome page routeRoute::get('/', function () { return view('welcome');});
// Route with a required ID parameterRoute::get('/product/{id}', function ($id) { return 'Product ID: ' . htmlspecialchars($id);});
// Route with an optional name parameterRoute::get('/greet/{name?}', function ($name = 'Visitor') { return 'Hello, ' . htmlspecialchars($name) . '!';});Testing these routes:
- Visit
http://localhost:8000/: The browser will display the default Laravel welcome page. - Visit
http://localhost:8000/product/123: The browser will display ‘Product ID: 123’. - Visit
http://localhost:8000/greet/John: The browser will display ‘Hello, John!’. - Visit
http://localhost:8000/greet/: The browser will display ‘Hello, Visitor!’ because thenameparameter is optional and defaults to ‘Visitor’.
Regular Expression Constraints
Section titled “Regular Expression Constraints”You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained:
Route::get('/user/{name}', function ($name) { //})->where('name', '[A-Za-z]+');
Route::get('/user/{id}', function ($id) { //})->where('id', '[0-9]+');
Route::get('/user/{id}/{name}', function ($id, $name) { //})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);For more advanced routing topics, including Named Routes, Route Groups, Route Model Binding, and Rate Limiting, refer to the official Laravel documentation on Routing.