Learn the route of Laravel from me

  • 2021-07-22 09:12:52
  • OfStack

Basic routing

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

Basic GET routing


Route::get('/', function()
{
    return 'Hello World';
});

Basic POST routing


Route::post('foo/bar', function()
{
    return 'Hello World';
});

Register a route that can respond to any HTTP action


Route::any('foo', function()
{
    return 'Hello World';
});

Support only HTTPS routing


Route::get('foo', array('https', function()
{
    return 'Must be over HTTPS';
}));

In actual development, it is often necessary to generate URL according to route, and URL:: to method can meet this requirement:

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

Routing parameters


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

Optional routing parameters


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

Optional routing parameters with default values


Route::get('user/{name?}', function($name = 'John')
{
    return $name;
});

Routing parameters qualified by regular expressions


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

Pass a parameter-qualified array

Of course, if necessary, you can also pass an array containing parameter qualifications as parameters:


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

Define a global schema

If you want to qualify routing parameters globally with a specified regular expression, you can use the pattern method:


Route::pattern('id', '[0-9]+'); Route::get('user/{id}', function($id)
{
    // Only called if {id} is numeric.
});

Access routing parameters

If you want to access the routing parameters outside the scope of the route, you can use the Route:: input method:


Route::post('foo/bar', function()
{
    return 'Hello World';
});
0

Routing filter

Routing filters provide a very convenient way to restrict access to certain features in your application, such as those that require authentication to access. The Laravel framework itself already provides a number of filters, including auth filters, auth. basic filters, guest filters, and csrf filters. These filters are defined in the app/filter. php file.

Define 1 routing filter


Route::post('foo/bar', function()
{
    return 'Hello World';
});
1

If an response is returned from the route filter, the response will be considered to correspond to the current request, the route will not be executed, and any code defined after the filter in the route will not be executed.

Bind a filter for a route


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

Bind the filter to the controller Action


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

Bind multiple filters for routes


Route::post('foo/bar', function()
{
    return 'Hello World';
});
4

Specify filter parameters


Route::post('foo/bar', function()
{
    return 'Hello World';
});
5

All subsequent filters will receive $response as the third parameter:


Route::post('foo/bar', function()
{
    return 'Hello World';
});
6

Pattern-based filter

You can also specify filters for URI for Group 1 routes.


Route::post('foo/bar', function()
{
    return 'Hello World';
});
7

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

Mode filters can also be qualified for HTTP actions:


Route::post('foo/bar', function()
{
    return 'Hello World';
});
8

Filter class

In advanced usage of filters, classes can also be used instead of closure functions. Since filter classes are resolved through IoC container, you can use dependency injection (dependency injection) in these filters to achieve better testing capabilities.

Define 1 filter class


Route::post('foo/bar', function()
{
    return 'Hello World';
});
9

Register filter class


Route::any('foo', function()
{
    return 'Hello World';
});
0

Named route

When redirecting and generating URL, it is more convenient to use named routes. You can specify 1 name for the route, as follows:


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

You can also specify a route name for controller action:


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

Now, you can use the route name to create URL and redirect:


$url = URL::route('profile'); $redirect = Redirect::route('profile');

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


$name = Route::currentRouteName();

Routing group

Sometimes you may need to apply filters for a group of routes. Using routing groups avoids specifying filters separately for each route:


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 wildcard parameters in domain names:

Register subdomain routing


Route::group(array('domain' => '{account}.myapp.com'), function()
{     Route::get('user/{id}', function($account, $id)
    {
        //
    }); });

Routing prefix

You can prefix group routes through the prefix property:

Setting Prefixes for Routing Groups


Route::any('foo', function()
{
    return 'Hello World';
});
7

Routing and model binding

Model binding provides a convenient way to inject model instances into routing. For example, instead of injecting only user ID, you can inject the entire model instance matching user ID into the route. First, specify the model to be injected using the Route:: model method:

Will refer to a model

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


Route::any('foo', function()
{
    return 'Hello World';
});
8

Since we have bound the {user} parameter to the User model, we can inject 1 User instance into the route. For example, access to profile/1 injects an User instance with ID of 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:


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

If you want to resolve the routing parameters yourself, just use the Route:: bind method:


Route::get('foo', array('https', function()
{
    return 'Must be over HTTPS';
}));
0

Throw 404 error

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


Route::get('foo', array('https', function()
{
    return 'Must be over HTTPS';
}));
1

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

More information about handling 404 exceptions and customizing the response when an error occurs can be found in the error documentation.

Controller routing

Laravel not only provides the function of using closure function to handle routing, but also can route to the controller, and even supports the creation of resource controllers.


Related articles: