Regular Expression Route Constraints And Route Names in Laravel 5.4

You can use regular expressions to define that a route should only match if a parameter meets particular requirements.

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

Route::get('users/{username}', function ($username) {
//
})->where('username', '[A-Za-z]+');

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

If you visit a URI that matches a path, but the regex doesn’t match the parameter, it won’t be matched. So users/abc in the example above would skip the first Closure, but it would be matched by the second Closure, so it would get routed there. On the other hand, posts/abc/123 wouldn’t match any of the Closures, so it would give a 404.

Route Names

Laravel also allows you to name each route, which enables you to refer to it without explicitly referencing the URL.

// app/Http/routes.php
Route::get('members/{id}', [
    'as' => 'members.show',
    'uses' => 'MembersController@show'
]);
// view file
<a href="<?php echo route('members.show', ['id' => 14]); ?>">

We passed a configuration array to the second parameter instead of a string. Laravel checks the type of the second parameter and routes accordingly; if it’s a Closure, it runs it; if it’s a string, it assumes
it’s the identification of a controller and method; and if it’s an array, it expects to get enough parameters from the array that it can resolve the route. 'as' allows to name the route. 

Gist URL to code is https://gist.github.com/isurum/736baf5fde1c8c3cc339058f9bdefa4b

Comments

Popular posts from this blog

Offers on Friday, April 24, 2020

Fatal: LoadModule: error loading module 'mod_sql_mysql.c'