Router _ php instance for Laravel

Source: Internet
Author: User
Tags subdomain
This article mainly introduces the concept and example of Lavarvel framework routing, which is very practical. If you need it, you can refer Basic route

Most paths in an application are defined in the app/routes. php file. The simplest Laravel routing consists of URI and closure callback functions.

Basic GET route

The Code is as follows:


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

Basic POST route

The Code is as follows:


Route: post ('foo/bar', function ()
{
Return 'Hello world ';
});

Register a route that can respond to any HTTP action

The Code is as follows:


Route: any ('foo', function ()
{
Return 'Hello world ';
});

Only HTTPS routes are supported.

The Code is as follows:


Route: get ('foo', array ('https', function ()
{
Return 'ust be over https ';
}));

In actual development, you often need to generate a URL Based on the route. The URL: to method can meet this requirement:

$ Url = URL: to ('foo ');

Route Parameters

The Code is as follows:


Route: get ('user/{id} ', function ($ id)
{
Return 'user'. $ id;
});

Optional route Parameters

The Code is as follows:


Route: get ('user/{name ?} ', Function ($ name = null)
{
Return $ name;
});

Optional route parameters with default values

The Code is as follows:


Route: get ('user/{name ?} ', Function ($ name = 'john ')
{
Return $ name;
});

Route parameters restricted by regular expressions

The Code is as follows:


Route: get ('user/{name} ', function ($ name)
{
//
})
-> Where ('name', '[A-Za-z] + ');

Route: get ('user/{id} ', function ($ id)
{
//
})
-> Where ('id', '[0-9] + ');

Array with parameter limitations passed

Of course, if necessary, you can also pass an array containing the parameter limitation as a parameter:

The Code is as follows:


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

Define global Mode

If you want to use a specified regular expression to limit route parameters globally, you can use the pattern method:

The Code is as follows:


Route: pattern ('id', '[0-9] + ');

Route: get ('user/{id} ', function ($ id)
{
// Only called if {id} is numeric.
});

Access route Parameters

If you want to access Route parameters outside the Route range, you can use the Route: input method:

The Code is as follows:


Route: filter ('foo', function ()
{
If (Route: input ('id') = 1)
{
//
}
});

Route Filter

The routing filter provides a very convenient way to restrict access to certain functions in the application. For example, it is very useful for functions that require verification. The Laravel framework itself provides some filters, including auth filters, auth. basic filters, guest filters, and csrf filters. These filters are defined in the app/filter. php file.

Define a route Filter

The Code is as follows:


Route: filter ('Old', function ()
{
If (Input: get ('age') <200)
{
Return Redirect: to ('home ');
}
});

If a response is returned from the route filter, the response is considered to be the request, and the route will not be executed, all codes defined in this filter in this route will not be executed.

Bind a filter to a route

The Code is as follows:


Route: get ('user', array ('before' => 'old', function ()
{
Return 'you are over 200 years old! ';
}));

Bind the filter to the Controller Action

The Code is as follows:


Route: get ('user', array ('before' => 'old', 'uses '=> 'usercontroller @ showProfile '));

Bind multiple filters to a route

The Code is as follows:


Route: get ('user', array ('before' => 'auth | old', function ()
{
Return 'you are authenticated and over 200 years old! ';
}));

Filter parameters

The Code is as follows:


Route: filter ('age', function ($ route, $ request, $ value)
{
//
});

Route: get ('user', array ('before' => 'Age: 200 ', function ()
{
Return 'Hello world ';
}));

All subsequent filters receive $ response as the third parameter:

The Code is as follows:


Route: filter ('log', function ($ route, $ request, $ response, $ value)
{
//
});

Pattern-based Filter

You can also specify a filter for a group of routes on the URI.

The Code is as follows:


Route: filter ('admin', function ()
{
//
});

Route: when ('admin/* ', 'admin ');

In the above case, the admin filter will be applied to all routes starting with admin. An asterisk is a wildcard that matches any combination of multiple characters.

You can also filter the HTTP action restriction mode:

The Code is as follows:


Route: when ('admin/* ', 'admin', array ('post '));

Filters

In the advanced usage of filters, classes can also be used to replace closure functions. Since the filter class is parsed through IoC container, you can use the dependency injection method in these filters to achieve better testing capabilities.

Define a filter class

The Code is as follows:


Class FooFilter {

Public function filter ()
{
// Filter logic...
}

}

Register a filter

The Code is as follows:


Route: filter ('foo', 'foofilter ');

Named route

It is more convenient to use named routing when redirecting and generating URLs. You can specify a name for the route as follows:

The Code is as follows:


Route: get ('user/profile ', array ('as' => 'profile', function ()
{
//
}));

You can also specify the route name for the controller action:

The Code is as follows:


Route: get ('user/profile ', array ('as' => 'profile', 'uses '=> 'usercontroller @ showProfile '));

Now, you can use the route name to create URLs and redirection:

The Code is as follows:


$ Url = URL: route ('profile ');

$ Redirect = Redirect: route ('profile ');

You can use the currentRouteName method to obtain the name of the currently running route:

The Code is as follows:


$ Name = Route: currentRouteName ();

Route Group

Sometimes you may need to apply a filter for a group of routes. You can avoid specifying a filter for each route by using a routing group:

The Code is as follows:


Route: group (array ('before' => 'auth'), function ()
{
Route: get ('/', function ()
{
// Has Auth Filter
});

Route: get ('user/profile ', function ()
{
// Has Auth Filter
});
});

Subdomain Routing

The routing function in Laravel also supports wildcard subdomain names. You can specify the wildcard parameter in the Domain Name:

Register a subdomain Routing

The Code is as follows:


Route: group (array ('domain '=>' {account} .myapp.com '), function ()
{

Route: get ('user/{id} ', function ($ account, $ id)
{
//
});

});

Route prefix

You can use the prefix attribute to set the prefix for a group route entry:

Set a prefix for a route group

The Code is as follows:


Route: group (array ('prefix' => 'admin'), function ()
{

Route: get ('user', function ()
{
//
});

});

Route and model binding

Model binding provides a convenient way to inject model instances into a route. For example, you can inject the entire model instance that matches the user ID into the route, rather than just the user ID. First, use the Route: model Method to specify the model to be injected:

Input a model

Route: model ('user', 'user ');
Then, define a route containing the {user} parameter:

The Code is as follows:


Route: get ('profile/{user} ', function (User $ user)
{
//
});

Since the {user} parameter has been bound to the User model, a User instance can be injected into the route. For example, access to profile/1 will inject the User instance with ID 1 into the route.

Note: If the corresponding model instance cannot be matched in the database, the 404 error will be thrown.
If you want to customize the "not found" behavior, you can pass a closure function as the third parameter of the model method:

The Code is as follows:


Route: model ('user', 'user', function ()
{
Throw new NotFoundException;
});

If you want to resolve Route parameters yourself, you only need to use the Route: bind method:

The Code is as follows:


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

Throw 404 error

There are two ways to manually trigger the 404 error from the route. First, you can use the App: abort method:

The Code is as follows:


App: abort (404 );

Second, you can throw a Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException.

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.