Laravel HTTP Routing

Source: Internet
Author: User

Routing configuration file

Definition: A route is a Uniform Resource Identifier (URI) that parses a request from a client and distributes the request to the expected processing logic (matching the request address) according to the rules set, which is the routing rule, and this process is the route.

Route::get ('/', function () {
Return view (' index ');
});

We visit http://yourdoamin/to display the content of the rendered view file index. This is very concise for the production of a website home page, no need to create additional controllers. Of course, if the home page is part of a class of organizational methods, it can also be implemented with a controller.

Direct access to static pages:

Route::get (' About ', function () {
Return view (' about ');
});

Access to the About page via address http://yourdomain/about, which is defined within the view about file.

Routing configuration file location: app/http/routes.php. Most basic Laravel routes accept only one URI and one (Closure (Closure), anonymous function? ) parameter

such as closures (usually rarely used):

Go to the Web site root to output Hello World

Route::get ('/', function () {
Return ' Hello world ';
});

Basic Get Examples:

Specifies the Get method to access the http://Domain name. com/test, the route points to the index method of the TestController controller below/app/http/controllers.

Route::get ('/test ', ' testcontroller@index ');

If the project is large, the controllers will usually be grouped (just create a new group directory under the/app/http/controllers directory). such as:/app/http/controllers/shop

Route::get ('/shop ', ' shop/testcontroller@index ');

Route access Mode

You can specify how routes are accessed: Get, post, put, delete. The access method is specified and other access will cause an error.

Route::get ('/', function () {
Return ' Hello world ';
});
Route::p ost ('/', function () {
Return ' Hello world ';
});
Route::p ut ('/', function () {
Return ' Hello world ';
});
Route::d elete ('/', function () {
Return ' Hello world ';
});

You can also specify multiple access methods

As follows: will allow get or post access

Route::match ([' Get ', ' post '], '/', function () {
Return ' Hello world ';
});
Route::match ([' Get ', ' post '], '/shop ', ' shop\shopcontroller@index ');

Specify any way to access

Route::any (' foo ', function () {
Return ' Hello world ';
});
Route::any ('/shop ', ' shop\shopcontroller@index ');

Get the URL address http://homestead.app/shop

$url = URL (' shop ');

Access mode spoofing (method spoofing)

Usually HTML forms do not support put or delete requests, and we can spoof the way that put DELETE can access

When called in an HTML form, you will need to add a hidden _method field in the form. The value that corresponds to the _method field sent is treated as an HTTP request method

Such as:

CSRF Protection

To protect the program from CSRF (cross-site request forgery) attacks, Laravel automatically places random tokens in each user's session, which is used to ensure that authenticated users are actually making requests to the application.

Insert CSRF Token into form

Used in templates

We do not need to manually verify the CSRF token of a POST, PUT, DELETE request.

The Verifycsrftoken HTTP middleware automatically validates tokens by storing the token pairing of the requested input in the session.

X-csrf-token

In addition to looking for CSRF token as the "post" parameter, the middleware also checks the X-xsrf-token request header.

For example, you can store token in the META tag and use JQuery to add it to all the request headers:

 
  

The Jquery.ajaxsetup () method sets the global AJAX default option.

$.ajaxsetup ({headers: {' X-csrf-token ': $ (' meta[name= ' csrf-token ') '). attr (' content ')}});

All AJAX requests are automatically added to the CSRF token:

$.ajax ({url: "/foo/bar",})

Route parameters

Base route parameters (no parameters are error)

Route::get ('/user/{id} ', function ($id) {    return ' user '. $id;}); Route::get ('/shop/{id} ', ' Shop\shopcontroller@index ');

In the Controller method

function Index ($id) {    echo $id}

Note: Routing parameters cannot contain-characters. Use underscore instead (_).

Selectable Routing Parameters

Route::get ('/shop/{id} ', function ($id = null) {    

In the Controller method

Function index ($id =null) {    echo $id}

Route parameters with default values

Route::get ('/shop/{id} ', function ($id = 1) {    

In the Controller method

Function index ($id =1) {    echo $id}

Restricting parameters with regular expressions

Route::get (' user/{name} ', function ($name) {    return $name;}) ->where (' name ', ' [a-za-z]+ ');//The limit parameter can only be uppercase and lowercase letters route::get (' User/{id} ', function ($id) {    return $id;})

->where (' id ', ' [0-9]+ ');//The limit parameter can only be a number

Using multiple criteria to restrict an array

Route::get (' user/{id}/{name} ', function ($id, $name) {    //})->where ([' id ' = ' = ' [0-9]+ ', ' name ' = ' = ' [a-z]+ '])

Defining the Global Schema

Use the pattern method. Define the schema in the boot method of the App/providers/routeserviceprovider:

$router->pattern (' id ', ' [0-9]+ ');

Once the pattern is defined, it acts on all routes that use this particular parameter:

Route::get (' User/{id} ', function ($id) {    //only {ID} is a number to be called. });

The route alias. (easy to generate URLs and redirects)

Route::get (' User/profile ', [' as ' = ' profile ', function () {    //}]);

Specify the route name for the controller action:

Route::get (' Shop/index ', [    ' as ' + ' center ', ' uses ' = ' shop\shopcontroller@index ']);

Used in the controller

$url = route (' center '); Echo $url;  Http://homestead.app/shop/index$redirect = Redirect ()->route (' center '); Echo $redirect; redirect

The Currentroutename method returns the currently requested route name: $name = Route::currentroutename ();

Controller routing

Controller routing I think the main problem is to solve the complexity of routing, because the large-scale application business complex, the controller is quite much, we can not each controller method to define a route. Laravel controller routing can solve the problem perfectly

Route::controller ('/', ' HomeController ');

The way the controller is written is also subject to change:

/** * Show Home page. * * @return Response */public function GetIndex () {    return view (' Home ');} /** * Display About Interface * * @return Response */public function Getabout () {    return view (' about ');}

Prefix get,post, any, etc.

Resource Controller

The Laravel resource controller has native support for RESTful architectures. In fact, there is no direct difference between the Laravel resource controller and other controllers, but the method and structure of the Controller class is slightly stipulated, but we do not have to manually create a resource controller, we can use the Laravel command line tool?? Artisan

PHP Artisan Make:controller Articlecontroller

You can create a resource controller named Articlecontroller, with the file default under App/http/controllers. We opened the articlecontroller.php and found that many methods have been written, such as index, create, show, and so on. What is the meaning of the distinction? How can i access the routing definition?

Route::resource (' article ', ' Articlecontroller ');

What about the address rules for access? If you already know about RESTful, then read the official documents below, and you'll understand the basics. I have the above controller, routing, to illustrate. Look at a table first:

The meaning of the Controller method represented by the request method request URI
GET /article Index Index/List
GET /article/create Create Create (show form)
POST /article Store Save the data you created
GET /article/{id} Show Display the contents of the corresponding ID
GET /article/{id}/edit Edit Edit (Show form)
Put/patch /article/{id} Save Save the data you edit
DELETE /article/{id} Destroy Delete

When a resource is defined for route route::resource (' article ', ' Articlecontroller ');

Access address http://yourdomain/article, equivalent to the index method of the access controller Articlecontroller.

Access to the address Http://yourdomain/article/create will be accessed to the Create method.

Submitting data via POST to address http://yourdomain/article is equivalent to being processed by the store method.

Routing groups

Middleware Routing Middleware

The $middleware array in app/http/kernel.php is the global middleware, that is, any route will be applied to these middleware, such as the CSRF verification middleware inside.

Sometimes we do not need the global middleware, this time you can register a middleware to the app/http/kernel.php file in the $routeMiddleware array, the array's key name is the middleware alias, the key value is the specific middleware class, such as

' Auth ' = ' app\http\middleware\authmiddleware '

Our $routeMiddleware array in the app/http/kernel.php file registers a separate middleware that can be used to bind to a routing and routing group alone. The route definition can look like this:

Route::get (' Admin/profile ', [' middleware ' = ' auth ', function () {    //}]);

When we visit Http://yourdomain/admin/profile, we first go through the global middleware, and then we define the name auth in the app/http/kernel.php $routeMiddleware array. of middleware.

The middleware parameter in the group shared attributes array defines the list of middleware that will be applied to all routes within the group.

The middleware will be executed in the order specified in the list:

Route::group ([' Middleware ' = [' foo ', ' Bar ']], function () {        route::get ('/'), function () {                //has Foo and bar Mid Dleware     });        Route::get (' User/profile ', function () {                //has Foo and Bar middleware     });

Namespace routing namespaces

Use the namespace parameter in the group attribute array to specify the namespace of the controller in this group:

Route::group ([' namespace ' = ' Admin '], function () {        ///Controllers within the "App\http\controllers\admin" Namespace     route::group ([' Namespace ' = ' User '], function () {                //Controllers within the "app\http\ Controllers\admin\user "Namespace     }");

Note: By default, App/providers/routeserviceprovider contains routes.php files that have built-in your namespace groups without the use of the full app\http\controllers namespace prefix to register controller routing.

Sub-domain Routing

Route::group ([' domain ' = ' {Account}.homestead.app '], function () {      route::get (' shop/{id} ', Function ($account , $id) {                return ' domain: '. $account. ' ===='.' ID: '. $id;        });});

Visit: Http://myapp.homestead.app/shop/users

Route prefixes

Route::group ([' prefix ' = ' shop '], function () {        route::get (' Users ', function () {             //return 111;         Matches the "/admin/users" URL     });

Visit: Homestead.app/shop/users

Register a URL parameter to the route prefix

Route::group ([' prefix ' = ' shop/{account_id} '], function () {        route::get (' Users ', function ($account _id) {                return $account _id;                //     });});

Visit: Homestead.app/shop/22/users

You can even define a limit for a named parameter in the prefix:

Route::group ([          ' prefix ' = ' shop/{account_id} ',             ' where ' = [' account_id ' = ' = ' [0-9]+ '],      ],      function () {            route::get (' Users ', function ($account _id) {                    return $account _id;                    //    });});

Visit: Homestead.app/shop/22/users

Routing model bindings

Laravel model binding provides a convenient way to inject model entities into your route.

For example, rather than injecting a user ID, you can choose to inject a user class entity that matches a given ID.

Use the model method of the route to specify the class to which the specific parameters are to be defined, and the App/providers/routeserviceprovider::boot method defines your model bindings:

Public Function boot (Router $router) {    parent::boot ($router);    $router->model (' user ', ' App\user ');}

Then define a route with the {user} parameter:

Route::get (' Profile/{user} ', function (App\user $user) {    //});

Note: If a matching model entity is not found in the database, a 404 error is thrown.

If you want to customize the behavior of "not found", pass the closure as the third parameter into the model method:

Route::model (' user ', ' user ', function () {    throw new notfoundhttpexception;});

If you want to use the logic that you decide, you should use the Route::bind method.

Closures Pass the URI segment value through the Bind method and should return the class entity that you want to inject the route into:

Route::bind (' User ', function ($value) {    return user::where (' name ', $value)->first ();});

Throw a 404 error

Route::get ('/shop/{id} ', function ($id) {    //return ' User '. $id;    Abort (404);});

The controller uses the Abort helper function to manually trigger a 404 error.

Abort (404);

Custom error page

resources/views/errors/404.blade.php

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

  • 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.