Laravel5.2-httprouting learning

Source: Internet
Author: User
Tags array definition file url subdomain name webhook
Laravel5.2-httprouting

All Laravel routes are defined in the app/Http/routes. phpfile, which is automatically loaded by the framework. routes are stored in the routes. php file, and the laravel framework automatically loads the 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 http get method, or other methods such as post // receives a parameter whose url parameter is foo, add the closed anonymous function () {} return 'Hello World'; // use return in the function to return data to Route: get ('Foo ')});
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 will not have access to sessions and CSRF protection. a routing group without middleware cannot access sessions and CSRF protection, so make sure any routes that need these features are placed within the group. make sure that the routes that require these features are placed in the routing group, Typically, you will place most of your routes within this group:

Route: group (['ddleware '=> ['web'], function () {// This is the route group Route: group, this is middleware ['middleware Ware '=> ['web']});
Available Router Methods

The router allows you to register routes that respond to any HTTP verb:

Route: get ($ uri, $ callback); // This is get Route: post ($ uri, $ callback); // This is post Route: put ($ uri, $ callback); // This is put Route: patch ($ uri, $ callback); // The patch is special and unknown for the moment. Route: delete ($ uri, $ callback); // This is delete Route: options ($ uri, $ callback); // This is an example. you can use options to enter the required http Route request method.

Sometimes you may need to register a route that responds to multiple HTTP verbs. you may do so using the matchmethod. or, you may even register a route that responds to all HTTP verbs using the anymethod:

Route: match (['GET', 'post'], '/', function () {// This is the method that uses match to accept access, match the methods in the [] Array}); Route: any ('foo', function () {// This is acceptable for any method });
Route Parameters Required Parameters

1. URI is a unified resource identifier. it is a string used to identify an Internet resource name. This identifier allows users to interact with any (including local and internet) resources through a specific protocol. A uri is defined by a scheme that includes a definite syntax and related protocols. There are three components: the resource access naming mechanism, the host name for storing the resource, and the name of the resource itself, which are represented by the path.

For example, the file URL is represented by file on the server. the host IP address, file access path (directory), and file name must be followed. Sometimes the directory and file name can be omitted, but the "/" symbol cannot be omitted.

For example, file: // a: 1234/B/c/d.txtindicates that the obtained resource uses the ftpprotocol. the resource target is the d.txt under the c directory in the bdirectory of the 1234client of Avel.

2. URL is a unified resource positioning, a simple representation of the location and access method of resources that can be obtained from the Internet, and a standard resource address on the Internet. Each file on the Internet has a unique URL. it contains information that specifies 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 will need to capture segments of the URI within your route captures the variable in the uri, even if the variable can be passed in For example, you may need to capture a user's ID from the URL. you may do so by defining route parameters:

Route: get ('user/{id} ', function ($ id) {return 'user '. $ id; // Use {} to input a variable, pass the variable to the function parameter, function ($ id), and then pass it to the function body. you can return the value through return, similar to common functions });

You may define as your route parameters as required by your route:

Route: get ('posts/{post}/comments/{comment} ', function ($ postId, $ commentId) {// multiple parameters can be input in a url, you only need to be able to match the input function parameters one by one. });

Route parameters are always encased within "curly" braces (variables are enclosed in braces for transmission). The parameters will 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 you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing? Mark after the parameter name. Make sure to give the route's corresponding variable a default value:

Route: get ('user/{name ?} ', Function ($ name = null) {// supports default Variables. use? Specify the default value of the variable 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 may specify a name for a route using the asarray key when defining the route: name the route, specify a name for the route, and use as the array key to define

Route: get ('Profile ', ['as' => 'Profile', function () {// A named Route is defined here. the Route name is profile, you can use the route name profile}].

You may also specify route names for controller actions:

Route: get ('Profile ', ['as' => 'Profile', 'uses '=> 'usercontroller @ showProfile' // The Route name is specified here, also, specify the route name for the controller action. The controller action is @.]);

Alternatively, instead of specifying the route name in the route array definition, you may chain the namemethod onto the end of the route definition:

Route: get ('user/profile ', 'usercontroller @ showProfile')-> name ('Profile '); // you can use the name method to specify the Route name.
Route Groups & Named Routes

If you are using route groups, you may specify an askeyword in the route group attribute array, allowing you to set a common route name prefix for all routes within the group:

Route: group (['as' => 'admin: '], function () {// you can set a path name or a Route name prefix, here the prefix admin: Route: get ('dashboard', ['as' => 'dashboard', function () {// Route named "admin :: dashboard "}]); // because this group has the routing prefix admin:, the routing names are all prefixed. The Complete routing name here is admin :: dashboard });
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 routefunction:

// Generating URLs... $ url = route ('Profile '); // you can use the route name in general mode. here, you can use the global route method to obtain url information through the route name profile, assign $ url // Generating Redirects... return redirect ()-> route ('Profile '); // You can also generate redirection. use redirect () to call the route method to generate redirection and return

If the named route defines parameters, you may pass the parameters as the second argument to the routefunction. The given parameters will automatically be inserted into the URL in their correct positions:

Route: get ('user/{id}/profile ', ['as' => 'Profile', function ($ id) {//}]); // when a route contains parameters, you can use {} to pass the parameter $ url = route ('Profile ', ['id' => 1]); // Set the input parameter variable {id} above, that is, id is the variable. you can pass the parameter id in the route () method through the array, the result of passing the variable.
Route Groups

Route groups allow you to share route attributes. the routing group allows you to share Route attributes, such as middleware and namespace, such as middleware or namespaces, routing SS a large number of routes without needing to define those attributes on each inpidual (individual, separate) route. shared attributes are specified in an 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 will be executed in the order you define this array:

Route: group (['ddleware '=> 'auth'], function () {// assign a middleware auth to this routing group, the entire routing group will be affected by this middleware. for example, page permission authentication is useful. Route: get ('/', function () {// Uses Auth Middleware}); Route: get ('user/profile ', function () {// Uses Auth Middleware });});
Namespaces

Another common use-case for route groups is assigning the same PHP namespace to a group of controllers. assign a php namespace to a controller group. You may use the namespaceparameter in your group attribute array to specify the namespace for all controllers within the group:

Route: group (['namespace '=\> 'admin'], function () {// Controllers Within The "App \ Http \ Controllers \ Admin" Namespace // controller is included in The Namespace Admin Route :: group (['namespace' =\> 'user'], function () {// Controllers Within The "App \ Http \ Controllers \ Admin \ User" Namespace // controller is included in The Namespace User, and the User is in the Admin sub-layer });});

Remember, by default, the RouteServiceProviderincludes (introduced) your routes. phpfile within a namespace group, allowing you to register controller routes without specifying the full App \ Http \ Controllersnamespace prefix. so, we only 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 files are all in a namespace group. you can register a controller without specifying a full namespace prefix. you only need to use the part following App \ Http \ Controllers.

Sub-Domain Routing

Route groups may also be used to route wildcard (wildcard) sub-domains. 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 domainkey on the group attribute array:

Route: group (['domain '=>' {account} .myapp.com '], function () {// use domain as the array key, and the value is the subdomain name, the parameter account is passed in to implement the matching of sub-domain names, so as to control access according to the sub-domain part in the uri, Route: get ('user/{id }', function ($ account, $ id ){//});});
Route Prefixes

The prefixgroup 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: group (['prefix' => 'admin'], function () {// if a Route prefix is set, all routes contain this prefix, this simplifies The Route entry Route: get ('users', function () {// Matches The "/admin/users" URL }); // because of the prefix admin, the final route generated is the url of/admin/users });

You may 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 to protect your application from cross-site request forgery (CSRF) attacks. cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are already Med on behalf of an authenticated user.

CSRF is a cross-site request attack. to prevent this situation, a csrf token is added to the server to verify that the request comes from any source.

Laravel automatically generates the token for each active user session.

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

Anytime you define a HTML form in your application, you shoshould include a hidden CSRF token field in the form so that the CSRF protection middleware will be able to validate the request. to generate a hidden input field _ tokencontaining the CSRF token, you 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 some controls, components, or methods of laravel to automatically use the csrf_token and related verification

You do not need to manually verify the CSRF token on POST, PUT, or DELETE requests. the VerifyCsrfToken middleware, which is wrongly Ded in the webmiddleware group, will automatically verify that the token 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

Prevent some uris from being protected by csrf. for example, some external systems interact with local data.

Sometimes you may wish to exclude a set of URIs from CSRF protection. for example, if you are using Stripeto process payments and are utilizing their webhook system, you will need to exclude your webhook handler route from Laravel's CSRF protection.

You may exclude URIs by defining their routes outside of the webmiddleware group that is already in the default routes. phpfile, or by adding the URIs to the $ routproperty of the VerifyCsrfTokenmiddleware:

Two methods: one is to write these special page uris information to a route Group that is not included in the csrf function, for example, to write it to another routing Group, this routing Group serves these uris separately, and the middleware used does not have the csrf function. Another method is to exclude the uris in the VerifyCsrfToken middleware, which is written as follows:

<? Phpnamespace App \ Http \ Middleware; use Illuminate \ Foundation \ Http \ Middleware \ same as BaseVerifier; // use the Middleware named BaseVerifierclass extends BaseVerifier // inherit BaseVerifier, override VerifyCsrfToken {/*** The URIs that shoshould be excluded from CSRF verification. ** @ var array */protected $ exclude T = [// write the exclusion method to it, in a fixed format. 'Stripe/* ',];}
X-CSRF-TOKEN

In addition to checking for the CSRF token as a POST parameter, the Laravel VerifyCsrfTokenmiddleware will also check for the X-CSRF-TOKENrequest header. you cocould, for example, store the token in a "meta" tag:

 

Once you have created the entity AG, 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') // identifies csrf-token with meta tags, used for data transmission in javascript and in header }});
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, do this automatically for you. it is unlikely that you will need to use this value manually.

Route Model Binding

Model binding, for example, inserting a Eloquent model instance

Laravel route model binding provides a convenient way to 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 will automatically resolve type-hinted (type implication) Eloquent models defined in routes or controller actions whose variable names match a route segment name. For example: laravel automatically parses these implied models

Route: get ('api/users/{user} ', function (App \ User $ user) {// automatically parses App \ User Eloquent models and returns a $ user object, the $ user is consistent with the {user} In uris. if it is worthwhile, it is passed to the function. if the model cannot be found, 404 is automatically returned, in fact, this is equivalent to a normal value passed to the routing function, and this value is now replaced with 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 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 be automatically generated.

Customizing The Key Name

If you wowould like the implicit model binding to use a database column other than idwhen retrieving models, you may override 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 rewriting the getRouteKeyName method of the Eloquent model. here, you can change it to slug return 'Slug ';}
Explicit Binding

Show bindings

To register an explicit binding, use the router's modelmethod to specify the class for a given parameter. You shoshould 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 to a given parameter. here, an App \ user is bound to the User parameter}

Next, define a route that contains a {user} parameter:

$ Router-> get ('Profile/{user} ', function (App \ User $ user) {// then the {user} parameter can be used here. // because we have bound the {user} parameter to the App \ User model, the User instance will be injected into the route. Therefore, if the request URL is profile/1, a User instance with User ID 1 will be injected. });

Since we have bound the {user} parameter to the App \ Usermodel, a Userinstance will be injected into the route. so, for example, a request to profile/1 will inject the Userinstance 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 and redirected If no matching data is found.

Customizing The Resolution Logic

If you wish to use your own resolution logic, you shocould use the Route: bindmethod. the Closure you pass to the bindmethod will receive the value of the URI segment, and shoshould return an instance of the class you want to be injected into the route:

To use custom logic, you need to use the Route: bind method.

$ Router-> bind ('user', function ($ value) {// Here the user will be passed to the $ value of the closure, then return the return App \ User: where ('name', $ value)-> first (); // here an instance class} is returned });
Customizing The "Not Found" Behavior

Custom not found behavior

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; // pass the closure of the encapsulation behavior to the model method, and passed as the third parameter });
Form Method Spoofing

HTML forms do not support PUT, PATCHor DELETEactions. so, when defining PUT, PATCHor DELETEroutes that are called from an HTML form, you will need to add a hidden _ methodfield to the form. the value sent with the _ methodfield will be used as the HTTP request method:

Form does not support put patch delete. you can add a hidden field _ method to the form. in this way, the form will send this field to the server and the php server will recognize it.

 

To generate the hidden input field _ method, you 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 will return the route handling the current HTTP request, allowing you to inspect the full Illuminate \ Routing \ Routeinstance:

This method will return the http request being processed by the Route, allowing you to inject the complete Illuminate \ Routing \ Route instance

$route = Route::current();$name = $route->getName();$actionName = $route->getActionName();

You may also use the currentRouteNameand currentRouteActionhelper methods on the Routefacade to access the current route's name or action:

$name = Route::currentRouteName();$action = Route::currentRouteAction();

Please refer to the API documentation for both the underlying class of the Route facadeand Route instanceto review all accessible methods.

Reference:

Https://laravel.com/docs/5.2/routing

Http://laravelacademy.org/post/2784.html

This article was created by Peter yuan and is licensed on the Chinese mainland using the signature-non-commercial use 2.5. You need to contact the author before reprinting and referencing, and sign the author and indicate the source of the article. Teenagers like God» laravel5.2-http routing learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.