Laravel 5.4
Awesome Laravel
- Awesome Laravel (Chirag Gude)
Prologue
- Release Notes
- Upgrade Guide
Getting Started
- Installation
- Configuration
- Directory Structure
- Laravel Homestead
- valet
Architecture Concepts
- Request Lifecycle
- Service Container
- Service Providers
- Facades
The Basics
- Routing
- Errors & Logging
- Middleware
- CSRF Protection
- Controllers
- HTTP Requests
- HTTP Responses
- Views
- HTTP Session
- Validation
Frontend
- Blade Templates
- Localization
- JavaScript & CSS Scaffolding
- Compiling Assets (Laravel Mix)
Security
- Authentication
- API Authentication (Passport)
- Authorization
- Encryption
- Hashing
- Resetting Passwords
Digging Deeper
- Artisan Console
- Queues
- Package Development
- Task Scheduling
- Broadcasting
- Cache
- Collections
- Events
- File Storage
- helpers
- Notifications
Database
- Database Getting Started
- Database Query Builder
- Database Pagination
- Database Migrations
- Database Seeding
- Redis
Eloquent ORM
- Eloquent Getting Started
- Eloquent Relationships
- Eloquent Collections
- Eloquent Mutators
- Eloquent Serialization
Testing
- Testing Getting Started
- HTTP Tests
- Browser Tests (Laravel Dusk)
- Database Testing
- Mocking
- redirect
Official Packages
- Laravel Cashier
- Envoy Task Runner
- Laravel Scout
Routing
Basic Routing
The most basic Laravel routes simply accept a URI and a Closure
, providing a very simple and expressive method of defining routes
|
The Default Route Files
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.
Available Router Methods
The router allows you to register routes that respond to any HTTP verb:
|
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:
CSRF Protection
Any HTML forms pointing to POST
, PUT
, 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:
Route Parameters
Required Parameters
Of course, 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:
You may define as many route parameters as required by your route:
Route parameters are always encased within {}
braces and should consist of alphabetic characters. Route parameters may not contain a -
character. Use an underscore (_
) instead.
Optional Parameters
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ?
mark after the parameter name. Make sure to give the route’s corresponding variable a default value:
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:
Global Constraints
If you would like a route parameter to always be constrained by a given regular expression, you may use the pattern
method. You should define these patterns in the boot
method of your RouteServiceProvider
:
|
Once the pattern has been defined, it is automatically applied to all routes using that parameter name:
|
Named Routes
Named routes allow the convenient generation of URLs or redirects for specific routes. You may specify a name for a route by chaining the name
method onto the route definition:
|
You may also specify route names for controller actions:
Generating URLs To Named Routes
Once you have assigned a name to a given route, you may use the route’s name when generating URLs or redirects via the global route
function:
If the named route defines parameters, you may pass the parameters as the second argument to the route
function. The given parameters will automatically be inserted into the URL in their correct positions:
Route Groups
Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route. Shared attributes are specified in an array format as the first parameter to the Route::group
method.
Middleware
To assign middleware to all routes within a group, you may use the middleware
key in the group attribute array. Middleware are executed in the order they are listed in the array:
Namespaces
Another common use-case for route groups is assigning the same PHP namespace to a group of controllers using the namespace
parameter in the group array:
Remember, by default, the RouteServiceProvider
includes your route files within a namespace group, allowing you to register controller routes without specifying the full App\Http\Controllers
namespace prefix. So, you only need to specify the portion of the namespace that comes after the base App\Http\Controllers
namespace.
Sub-Domain Routing
Route groups may also be used to handle sub-domain routing. Sub-domains may be assigned route parameters just like route URIs, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the domain
key on the group attribute array:
Route Prefixes
The prefix
group attribute may be used to prefix each route in the group with a given URI. For example, you may want to prefix all route URIs within the group with admin
:
Route Model Binding
When injecting a model ID to a route or controller action, you will often query to retrieve the model that corresponds to that ID. Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user’s ID, you can inject the entire User
model instance that matches the given ID.
Implicit Binding
Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name. For example:
Since the $user
variable is type-hinted as the App\User
Eloquent model and the variable name matches the {user}
URI segment, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI. If a matching model instance is not found in the database, a 404 HTTP response will automatically be generated.
Customizing The Key Name
If you would like model binding to use a database column other than id
when retrieving a given model class, you may override the getRouteKeyName
method on the Eloquent model:
|
Explicit Binding
To register an explicit binding, use the router’s model
method to specify the class for a given parameter. You should define your explicit model bindings in the boot
method of the RouteServiceProvider
class:
Next, define a route that contains a {user}
parameter:
Since we have bound all {user}
parameters to the App\User
model, a User
instance will be injected into the route. So, for example, a request to profile/1
will inject the User
instance from the database which has an ID of 1
.
If a matching model instance is not found in the database, a 404 HTTP response will be automatically generated.
Customizing The Resolution Logic
If you wish to use your own resolution logic, you may use the Route::bind
method. The Closure
you pass to the bind
method will receive the value of the URI segment and should return the instance of the class that should be injected into the route:
Form Method Spoofing
HTML forms do not support PUT
, PATCH
or DELETE
actions. So, when defining PUT
, PATCH
or DELETE
routes that are called from an HTML form, you will need to add a hidden _method
field to the form. The value sent with the _method
field will be used as the HTTP request method:
|
You may use the method_field
helper to generate the _method
input:
Accessing The Current Route
You may use the current
, currentRouteName
, and currentRouteAction
methods on the Route
facade to access information about the route handling the incoming request:
Refer to the API documentation for both the underlying class of the Route facade and Route instance to review all accessible methods.