HTTP Routing
Basic Routing
All Laravel routes was defined in the App/http/routes.phpfile, which was automatically loaded by the framework. Routes are placed in routes The Laravel framework automatically loads this file in a. php file. The most basic Laravel routes simply accept a URI and a Closure, providing a very simple and expressive method of defining Routes
Route::get (' foo ', function () { //get is the Get method for HTTP, or other methods such as post //receive a parameter with a URL parameter of foo, plus the closure anonymous function () {} return ' Hello world '; Return data to Route::get (' foo ')} in function with return );
The Default Routes File
By default, the Routes.phpfile contains a single route as well as a route groupthat applies the Webmiddleware group to all Routes it contains. This middleware group provides session state and CSRF protection to routes.
Any routes not placed within the Web Middleware group would not have access to sessions and CSRF protection, routing groups without middleware cannot access the session and CSRF protection, so do sure any routes that need these features is placed within the group. You need to make sure that the routes that require these features are placed in the routing group, typically, and you'll place the most of the your routes within this group:
Route::group ([' middleware ' + = [' web ']], function () { //This is the routing group Route::group, which is the middleware [' middleware ' + = [' web ']});
Available Router Methods
The router allows you to register routes that respond to any HTTP verb:
Route::get ($uri, $callback); This is the get route::p Ost ($uri, $callback);//This is the post route::p ut ($uri, $callback);//This is the put route::p atch ($uri, $callback); Patch is special, temporarily unknown Route::d elete ($uri, $callback);//This is the delete route::options ($uri, $callback);//This is a sample, Options can be used to fill in the required HTTP routing request mode
Sometimes need to register a route this responds to multiple HTTP verbs. You could do so using the Matchmethod. Or, you may even register a route, this responds to all HTTP verbs using the Anymethod:
Route::match ([' Get ', ' post '], '/', function () { //This is a method that is accepted with match and matches the method in the [] array}); Route::any (' foo ', function () { //This is acceptable to any method});
Route Parameters
Required Parameters
1, URI is a Uniform resource identifier, is a string used to identify an Internet resource name. This type of identification allows users to interact with any resource, including local and internet, through a specific protocol. The URI is defined by a scheme that includes a determination of syntax and related protocols. Consists of three components: the naming mechanism for accessing the resource, the host name that holds the resource, and the name of the resource itself, represented by the path.
For example, the URL of the file, the server mode with file, followed by the host IP address, file access path (that is, directory) and filename and other information. Directories and file names can sometimes be omitted, but the "/" symbol cannot be omitted.
Example: File://a:1234/b/c/d.txt represents the acquisition of resources using the FTP protocol, the resource target is a host of the 1234 port of the B directory under the C directory under the D.txt.
2, the URL is a unified resource positioning, is to be available from the Internet, the location of resources and access methods of a concise expression, the Internet is the address of the standard resources. Each file on the Internet has a unique URL that contains information that indicates the location of the file and how the browser should handle it. For example, Baidu URL is http://www.baidu.com.
Of course, sometimes you'll need to capture segments of the URI within your route captures variables in the URI, even if the support variable is passed in for example Need to capture a user's ID from the URL. Defining route Parameters:
Route::get (' User/{id} ', function ($id) { return ' user '. $id; Use {} to pass in the variable, the variable is passed into the function parameters, function ($id), and then passed to the body, you can return the value by return, with the normal function use very similar});
Define as many route parameters as required by your route:
Route::get (' posts/{post}/comments/{comment} ', function ($postId, $commentId) { //supports passing multiple parameters within a URL, As long as you can correspond to the parameters of the function passed in one by one. });
Route parameters is always encased within "curly" braces (wrapping the variable in curly braces). The parameters'll be passed into your route's Closurewhen the route is executed.
Note:route parameters cannot contain the-character. Use an underscore (_) instead.
Optional Parameters
Occasionally need to specify a route parameter and make the presence of this route parameter optional. 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) { //support default variable, with? Representation, and then specify the default value of the variable in the function's passed in functions return $name;}); Route::get (' user/{name} ', function ($name = ' John ') { return $name;});
Named Routes
Named routes allow the convenient generation of URLs or redirects for specific routes. You can specify a name for a route using the Asarray key when defining the route: named Route, specifying a name for the route, using as as the array key to define
Route::get (' profile ', [' as ' + ' profile ', function () { //here defines a named route, the name of the route is profile, which can be used when routing name Profile}]);
Also specify route names for controller actions:
Route::get (' profile ', [' as ' + ' profile ', ' uses ' = ' usercontroller@showprofile ' //here Specifies the name of the route as profile , the controller action is given a routing name, and the controller action is at the back of the @);
Alternatively, instead of specifying the route name in the route array definition, your may chain the Namemethod onto the E nd of the route definition:
Route::get (' User/profile ', ' Usercontroller@showprofile ')->name (' profile ');//Using the name method to specify the route name can also be
Route Groups & Named Routes
If you is using the route groups, you could specify an Askeyword in the route group attribute array, allowing your to set a comm On route name prefix to all routes within the group:
Route::group ([' as ' = ' admin:: '], function () {//In addition to setting the path has a name, you can also set the route name prefix, here set the prefix admin:: route::get (' Dashboard ', [' as ' = ' dashboard ', function () { //Route named "admin::d ashboard" }]); Because this group has the route prefix admin:: So the inside of the routing name is prefixed with, here the full route name is admin::d Ashboard});
Generating URLs to Named Routes
Once you has assigned a name to a given route, you may use the route's name when generating URLs or redirects via the Glo Bal routefunction:
Generating URLs ... $url = route (' profile ');//Use the route name in the general way, where the global route method is used to get the URL information via the Routing name profile and assign the value to the generating redirects ... Return Redirect ()->route (' profile '); You can also generate a redirect, call the route method with redirect () to generate a redirect, and return with return
If the named route defines parameters, you could pass the parameters as the second argument to the Routefunction. The given parameters'll automatically be inserted to the URL in their correct positions:
Route::get (' User/{id}/profile ', [' as ' + ' profile ', function ($id) { //}]));//The parameter can be passed by {} When the route contains a parameter, \ n = Route (' profile ', [' id ' = 1]);//the variable to which the parameter is set is {ID}, i.e. the ID is a variable, then the parameter ID can be passed through the array in the route () method to achieve the result of passing the variable.
Route Groups
Route groups allow share route attributes, routing group allows sharing of routing properties such as middleware and namespaces, such as middleware or namespaces, across a large Number of routes without needing to define those attributes on each individual (individual, separate) route. Shared attributes is specified in a array format as the first parameter to the Route::groupmethod.
To learn more about route groups, we'll walk through several common use-cases for the feature.
Middleware
To assign middleware to all routes within a group, you may use the Middlewarekey in the group attribute array. Middleware'll be executed in the order you define this array:
Route::group ([' middleware ' = ' auth '], function () {//Assigned a middleware auth to this routing group, then the entire routing group will be affected by this middleware, such as some page permission authentication is very useful. route::get ('/', function () { //Uses Auth middleware }); Route::get (' User/profile ', function () { //Uses Auth middleware });
Namespaces
Another common use-case for route groups are assigning the same PHP namespace to a group of controllers. Assign a PHP namespace to a contr Oller Group, you could use the Namespaceparameter in your group attribute array to specify the namespace for all controllers with In the group:
Route::group ([' Namespace ' =\> ' Admin '], function () { //Controllers within the ' app\\http\\controllers\\admin ' Namespace //controller contained within the namespace admin route::group ([' Namespace ' =\> ' User '], function () { /// Controllers within the "App\\http\\controllers\\admin\\user" Namespace //controller is contained within the namespace User, and user in the child layer of admin });
Remember, by default, the Routeserviceproviderincludes (introduced) your routes.phpfile within a namespace group, allowing you to r Egister controller routes without specifying the full app\http\\controllersnamespace prefix. So, we have need to specify the portion of the namespace that comes after the base app\http\\controllersnamespace.
Because by default, this routeserviceprovider introduces your routes.php file, all within a namespace group, allowing you to register a controller without specifying a full namespace prefix, only with app\http\ Controllers the back part.
Sub-domain Routing
Route groups may also is used to route wildcard (wildcard character) sub-domains. Sub-domains May is assigned route parameters just like Route URIs, allowing your to capture a portion of the sub-domain for Usage in your route or controller. The sub-domain is specified using the Domainkey on the group attribute array:
Route::group ([' domain ' = ' = ' {account}.myapp.com '], function () { ///use domain as the array key, then the value is the subdomain, and the parameter account is passed in, This implements the sub-domain name matching, which enables the control of access based on the sub-domain part of the URI, route::get (' user/{id} ', function ($account, $id) { // });});
Route prefixes
The Prefixgroup attribute is used to prefix each of the route in the group with a given URI. For example, want to prefix all route URIs within the group with admin:
Route::group ([' prefix ' = ' admin '], function () { //set a route prefix, all routes will contain this prefix, simplifying some of the same route input route::get (' Users ', function () { ///Matches the "/admin/users" URL }); Because of the prefix admin, the final route is generated by the/admin/users URL});
Also use the prefixparameter to specify common parameters for your grouped routes:
Route::group ([' prefix ' =\> ' accounts/{account\_id} '], function () { route::get (' detail ', function ($accountId) { //Matches the "/accounts/{account\_id}/detail" URL });
CSRF Protection
Introduction
Laravel makes it easy-protect your application from Cross-site request forgery (CSRF) attacks. Cross-site request forgeries is a type of malicious exploit whereby unauthorized commands is performed on behalf of a uthenticated user.
CSRF is a cross-site request attack, in order to prevent this, a CSRF token is added to the server side to verify that the request is from any source.
Laravel automatically generates this token for each active user session
Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token was used to verify the authenticated user are the one actually making the requests to the application.
Anytime define a HTML form in your application, you should include a hidden CSRF token field in the form so the The C SRF Protection Middleware is able to validate the request. To generate a hidden input field _tokencontaining The CSRF token, your may use the Csrf_fieldhelper function:
Vanilla php <? php echo Csrf_field ();?> PHP syntax//Blade template Syntax {{Csrf_field ()}} Blade template syntax
The Csrf_fieldhelper function generates the following HTML:
Call Laravel Some of the controls, components, or some methods of the time back automatically using the Csrf_token and related validation of the
You don't need to manually verify the CSRF tokens on POST, PUT, or DELETE requests. The Verifycsrftoken middleware, which is included in the Webmiddleware group, would automatically verify that the tokens in The request input matches the token stored in the session.
Verify that the middleware of Scrftoken is included in the Web middleware group by default, so it can be used immediately.
Excluding URIs from CSRF Protection
Avoid some URIs being csrf protected, such as some external systems interacting with local data.
Sometimes wish to exclude a set of URIs from CSRF protection. For example, if you is using Stripeto process payments and is utilizing their webhook system, you'll need to exclude Y Our Webhook handler route from Laravel ' s CSRF protection.
Exclude URIs by defining their routes outside of the Webmiddleware group, that's included in the default routes.ph Pfile, or by adding the URIs to the $exceptproperty of the Verifycsrftokenmiddleware:
Two methods: One is to write these special page URIs information to a routing group that has no CSRF functionality, such as writing to another routing group, which serves these URIs individually, and the middleware used does not have CSRF functionality. Another way is to verifycsrftoken this middleware within the URIs exclusion, the wording is as follows:
< Phpnamespace App\http\middleware;use Illuminate\foundation\http\middleware\verifycsrftoken as BaseVerifier;// Using the Verifycsrftoken middleware, and named Baseverifierclass Verifycsrftoken extends Baseverifier//Inherit Baseverifier, Rewrite verifycsrftoken{ /** * The URIs that should is excluded from CSRF verification. * * @var array */ protected $except = [//write the exclusion method to the inside, fixed format. ' stripe/* ', ];}
X-csrf-token
In addition to checking for the CSRF token as a POST parameter, the Laravel Verifycsrftokenmiddleware would also check for The x-csrf-tokenrequest header. Could, for example, store the token in a "meta" tag:
Once you has created the metatag, you can instruct a library like JQuery to add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:
$.ajaxsetup ({ headers: { ' X-csrf-token ': $ (' meta[name= ' Csrf-token "] '). attr (' content ') // Use META tags to identify csrf-token, used in JavaScript for data transfer, and in the header of }});
X-xsrf-token
Laravel also stores the CSRF token in a xsrf-tokencookie. You can use the cookie value to set the X-xsrf-tokenrequest header. Some JavaScript frameworks, like Angular, does this automatically for you. It is unlikely so you'll need to use this value manually.
Route Model Binding
Model bindings, such as inserting a eloquent model instance
Laravel Route model Binding provides a convenient-inject model instances into your routes. For example, instead of injecting a user's ID, you can inject the entire Usermodel instance that matches the given ID.
Implicit Binding
Laravel would automatically resolve type-hinted (type hint) eloquent models defined in routes or controller actions whose VARIABL E names match a route segment name. For Example:laravel will automatically parse these suggestive models
Route::get (' Api/users/{user} ', function (App\user $user) {//Auto parse App\user Eloquent models, returns a $user object, and this $ User is the same as the {user} inside the URIs, there is worth words and then passed to the function, if this model can not find worthy words, will automatically return 404, in fact, this is equivalent to a normal value passed to the function of the route, This value is now replaced by a laravel model, simplifying the code logic return $user->email;});
In this example, since the eloquent type-hinted $uservariable defined on the route matches the "User}segment in the route ' S URI, Laravel would automatically inject the model instance that have an ID matching the corresponding value from the Reque St URI.
If A matching model instance is not found in the database, a 404 HTTP response would be automatically generated.
Customizing the Key Name
If you would like the implicit model binding to use a database column other than Idwhen retrieving models, you may Overrid E The getroutekeynamemethod on your eloquent model:
/** * Get The route key for the model. * * @return string */public function Getroutekeyname () {//You can change the name of the model binding by overriding the Getroutekeyname method of eloquent, which is changed to slug return ' slug ';}
Explicit Binding
Show Bindings
To register an explicit binding with the router ' s Modelmethod to specify the class for a given parameter. You should define your model bindings in the Routeserviceprovider::bootmethod:
In the routeserviceprovider.php file
Binding a Parameter to a Model
Public Function boot (Router $router) { parent::boot ($router); $router->model (' user ', ' app\user '); Use the model method to bind a class for a given parameter, where a app\user} is bound for the User parameter
Next, define a route that contains a {user}parameter:
$router->get (' Profile/{user} ', function (App\user $user) { //Then you can use the {user} parameter here //Because we have bound {user} parameter to App\ User model, the user instance is injected into the route. Therefore, if the request URL is PROFILE/1, it injects a user instance with a username of 1. });
Since we have bound the {User}parameter to the App\usermodel, a userinstance would be injected into the route. So, for example, a request to Profile/1will inject the userinstance which have an ID of 1.
If A matching model instance is not found in the database, a 404 HTTP response would be automatically generated. If no matching data is found, the 404 request is automatically generated and redirected.
Customizing the Resolution Logic
If you wish to use your own resolution logic, you should use the Route::bindmethod. The Closure you pass to the Bindmethod would receive the value of the URI segment, and should return an instance of the CLA SS you want to is injected into the route:
If you want to use custom logic, you need to use the Route::bind method
$router->bind (' User ', function ($value) {///This will pass the user to the $value of the closure and return the class instance you want to inject in the route return App\user::where (' Name ', $value)->first (); This returns an instance of Class});
Customizing the "Not Found" Behavior
Customizing the behavior of not found
If you wish to specify your own ' not found ' behavior, pass a Closure as the third argument to the Modelmethod:
$router->model (' user ', ' app\user ', function () { throw new Notfoundhttpexception; The closure of the encapsulated behavior is passed to the model method and passed as a third parameter});
Form Method Spoofing
HTML forms do not support PUT, Patchor deleteactions. So, when defining PUT, Patchor deleteroutes that is called from the HTML form, you'll need to add a hidden _methodfield to the form. The value sent with the _methodfield would be used as the HTTP request method:
The form form does not support put patch delete behavior, you can add a hidden field _method to the form, so that the form will send this field to the server, the PHP server will be recognized.
To generate the hidden input field _method, your may also use the Method_fieldhelper function:
< php echo Method_field (' PUT ');?>
Of course, using the Blade templating engine:
{{Method_field (' PUT ')}}
Accessing the current Route
The Route::current () method would return the Route handling the current HTTP request, allowing-inspect the full illum Inate\routing\routeinstance:
This method returns the HTTP request that the route is processing, allowing you to inject the full Illuminate\routing\route instance
$route = Route::current (); $name = $route->getname (); $actionName = $route->getactionname ();
Also use the Currentroutenameand currentrouteactionhelper methods on the Routefacade to access the current route ' s Name or action:
$name = Route::currentroutename (); $action = Route::currentrouteaction ();
Refer to the API documentation for both the underlying class of the route Facadeand Route Instanceto Review All ACC Essible methods.
Reference:
Https://laravel.com/docs/5.2/routing
Http://laravelacademy.org/post/2784.html
This article was authored by Peteryuan and licensed under the Attribution-NonCommercial use of 2.5 mainland China. Please contact the author and the author and indicate the source of the article before reprint or citation. The same young»laravel5.2-http routing study