The router

Table des matières

By accessing to an URL (like http://127.0.0.1:8000/), Laravel will always execute the /routes/web.php script:

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
   return view('welcome');
});

This define that the / resource is a view called welcome.

Views are defined in the /resources/views/ folder. So, for the view welcome, there is a file called welcome.blade.php (Blade is the Laravel template engine, more info).

When showing the http://127.0.0.1:8000/ URL page, Laravel will then display then /resources/views/welcome.blade.php file.

1. Creating new routings

To add more routes, we then just need to add f.i.:

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

Then create a file /resources/views/about.blade.php and a “About us” content.

2. HTTP verbs

Route::get is called when the web server receives a GET verb so ... Route::post will be used for a POST and thus a form’s submission.

For instance:

Route::get('users', 'UsersController@getInfos');
Route::post('users', 'UsersController@postInfos');

The same URL http://localhost:8000/users will route to two different controllers depending on how the request was made:

Laravel recognizes GET, POST, PUT, DELETE, ... and also allow f.i. Route::any() for matching all methods.

3. Parameters

The way to retrieve parameters can be directly coded in the routing so, f.i.

can be managed by only one route:

Route::get('{n}', function($n) {
   return 'You are viewing page ' . $n . ' !';
})->where('n', '[1-3]');

The where is here just a demo purpose; we can filter allowed values with regex.

To accept any number:

})->where('n', '[0-9]+');

4. Naming route

By using the as keyword:

Route::get('/', ['as' => 'home', function () {
  return 'I am the homepage!';
}]);

Then, we can redirect to named route:

Route::get('accueil', function () {
  return redirect()->route('home');
});

5. Return a HTTP code

Just by using the response() function like:

Route::get('/', ['as' => 'home', function () {
   return response('Sorry no access to this page!', 403);
}]);

6. Tips

6.1. One route for all files

Imagine you wish to capture every access to, f.i., .html files in only one route.

Route::get('{file}.html', function (string $file) {
    echo 'You try to access to '.$file;
})->where(['file' => '[A-Za-z0-9\-_\/\ ]*']);

Thanks this route, you’ll be able to capture every access to .html whatever the folder (f.i. http://localhost/A/B/C/D/test.html).

The regex part allows:

6.2. See all existing routes

The following command will return a nice table with all known routes for an application.

php artisan route:list

For instance:

+--------+----------+-------------------------------+-----------------------+------------------------------------------------------------------------+----------------------------------------------+
| Domain | Method   | URI                           | Name                  | Action                                                                 | Middleware                                   |
+--------+----------+-------------------------------+-----------------------+------------------------------------------------------------------------+----------------------------------------------+
|        | GET|HEAD | /                             | home                  | App\Http\Controllers\HomeController@index                              | web,auth                                     |
|        | GET|HEAD | _debugbar/assets/javascript   | debugbar.assets.js    | Barryvdh\Debugbar\Controllers\AssetController@js                       | Barryvdh\Debugbar\Middleware\DebugbarEnabled |
|        | GET|HEAD | _debugbar/assets/stylesheets  | debugbar.assets.css   | Barryvdh\Debugbar\Controllers\AssetController@css                      | Barryvdh\Debugbar\Middleware\DebugbarEnabled |
|        | DELETE   | _debugbar/cache/{key}/{tags?} | debugbar.cache.delete | Barryvdh\Debugbar\Controllers\CacheController@delete                   | Barryvdh\Debugbar\Middleware\DebugbarEnabled |
|        | GET|HEAD | _debugbar/clockwork/{id}      | debugbar.clockwork    | Barryvdh\Debugbar\Controllers\OpenHandlerController@clockwork          | Barryvdh\Debugbar\Middleware\DebugbarEnabled |
|        | GET|HEAD | _debugbar/open                | debugbar.openhandler  | Barryvdh\Debugbar\Controllers\OpenHandlerController@handle             | Barryvdh\Debugbar\Middleware\DebugbarEnabled |
|        | GET|HEAD | api/user                      |                       | Closure                                                                | api,auth:api                                 |
|        | GET|HEAD | login                         | login                 | App\Http\Controllers\Auth\LoginController@showLoginForm                | web,guest                                    |
|        | POST     | login                         |                       | App\Http\Controllers\Auth\LoginController@login                        | web,guest                                    |
|        | POST     | logout                        | logout                | App\Http\Controllers\Auth\LoginController@logout                       | web                                          |
|        | POST     | password/email                | password.email        | App\Http\Controllers\Auth\ForgotPasswordController@sendResetLinkEmail  | web,guest                                    |
|        | POST     | password/reset                |                       | App\Http\Controllers\Auth\ResetPasswordController@reset                | web,guest                                    |
|        | GET|HEAD | password/reset                | password.request      | App\Http\Controllers\Auth\ForgotPasswordController@showLinkRequestForm | web,guest                                    |
|        | GET|HEAD | password/reset/{token}        | password.reset        | App\Http\Controllers\Auth\ResetPasswordController@showResetForm        | web,guest                                    |
|        | POST     | register                      |                       | App\Http\Controllers\Auth\RegisterController@register                  | web,guest                                    |
|        | GET|HEAD | register                      | register              | App\Http\Controllers\Auth\RegisterController@showRegistrationForm      | web,guest                                    |
|        | GET|HEAD | todo                          |                       | App\Http\Controllers\TodoController@getForm                            | web                                          |
|        | POST     | todo                          | storeTodo             | App\Http\Controllers\TodoController@postForm                           | web                                          |
|        | GET|HEAD | todo/{id}                     |                       | App\Http\Controllers\TodoController@show                               | web                                          |
|        | DELETE   | todo/{id}                     |                       | App\Http\Controllers\TodoController@delete                             | web                                          |
|        | PUT      | todo/{id}                     |                       | App\Http\Controllers\TodoController@edit                               | web                                          |
|        | GET|HEAD | todos                         | showTodos             | App\Http\Controllers\TodoController@index                              | web                                          |
+--------+----------+-------------------------------+-----------------------+------------------------------------------------------------------------+----------------------------------------------+

Very useful since we can see, for instance, for the route named todo that, based on the method, we’ll see: