Laravel Routing Basics and Advanced Features
This article provides a comprehensive guide to Laravel routing, covering basic route definitions, route files, HTTP verbs, CSRF protection, redirects, view routes, parameters with constraints, named routes, route groups, model binding, fallback routes, rate limiting, and form method spoofing, all illustrated with clear code examples.
Laravel routing can be defined with a simple URI and a Closure using Route::get('foo', function () { return 'Hello World'; });, providing an elegant way to handle requests.
All routes are stored in the routes directory; routes/web.php defines routes for the web middleware group (session, CSRF), while routes/api.php defines stateless routes assigned to the api middleware group.
The router supports the HTTP verbs get, post, put, patch, delete, and options. To respond to multiple verbs you can use Route::match(['get','post'], '/', function () { ... }); or Route::any('/', function () { ... });.
For POST, PUT, or DELETE requests, a CSRF token must be included in the form; otherwise the request will be rejected.
Redirect routes are created with Route::redirect('/here', '/there'); (default 302) or Route::redirect('/here', '/there', 301);. A permanent redirect can be defined with Route::permanentRedirect('/here', '/there');.
If a route only needs to return a view, use Route::view('/welcome', 'welcome'); or pass data with Route::view('/welcome', 'welcome', ['name' => 'Taylor']);.
Route parameters are placed inside {}. Required parameters are defined like
Route::get('user/{id}', function ($id) { return 'User '.$id; });. Optional parameters use a ? suffix and a default value, e.g.,
Route::get('user/{name?}', function ($name = null) { return $name; });. Constraints are added with where, e.g.,
Route::get('user/{id}', function ($id) { ... })->where('id', '[0-9]+');, and global patterns can be set in RouteServiceProvider::boot() using Route::pattern('id', '[0-9]+');.
Named routes simplify URL generation and redirection:
Route::get('user/profile', function () { ... })->name('profile');. URLs are generated with route('profile'); and redirects with return redirect()->route('profile');. Parameters are passed as the second argument to route().
Route groups share attributes such as middleware, namespace, domain, prefix, and name prefix. Example:
Route::middleware(['first','second'])->group(function () { Route::get('/', function () { ... }); });. Prefixes add a URI segment, and name prefixes add a dot‑separated string to route names.
Laravel offers route model binding. Implicit binding automatically injects a model instance when the route parameter name matches a type‑hinted variable, e.g.,
Route::get('api/users/{user}', function (App\User $user) { return $user->email; });. Explicit binding is registered in RouteServiceProvider::boot() with Route::model('user', App\User::class);. Custom logic can be provided via
Route::bind('user', function ($value) { return App\User::where('name', $value)->first() ?? abort(404); });or by overriding resolveRouteBinding on the model.
A fallback route catches all unmatched requests: Route::fallback(function () { ... });. It should be defined last.
Rate limiting is applied with the throttle middleware, e.g., Route::middleware('throttle:60,1')->group(...);. Dynamic limits can use a model attribute: throttle:rate_limit,1. Different limits for guests and authenticated users can be set with throttle:10|60,1.
HTML forms cannot send PUT, PATCH, or DELETE requests directly; instead include a hidden _method field or use the Blade directive @method('PUT') together with @csrf to spoof the HTTP verb.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
