Laravel Routing

Laravel Route is a way of creating a request URL of your application. These URL do not have to map to specific files on a website. The best thing about these URL is that they are both human readable and SEO friendly.

Routing is a core concept in Laravel, and it works a little differently than some of the frameworks of the past. The Laravel Route system is very flexible, and although a little tricky at first, once you get a good grasp of the fundamentals, you’ll find yourself asking how you lived without it all along. Without further ado, let’s dig into Laravel Routes!

The most basic Laravel routes simply accept a URI and a Closure, providing a very simple and expressive method of defining routes:

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

Laravel offers the following route methods:

  • get
  • post
  • put
  • delete
  • patch
  • options

which we can use as:

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

Named Route

Named routes allow the convenient generation of URLs or redirects for specific routes. You may specify a name for a route by chaining the name method onto the route definition:

Route::get('user/profile', function () {
    //
})->name('profile');

You may also specify route names for controller actions:

Route::get('user/profile', 'UserController@showProfile')->name('profile');

Route Groups

Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route. Shared attributes are specified in an array format as the first parameter to the Route::group method.

Middleware

To assign middleware to all routes within a group, you may use the middleware method before defining the group. Middleware are executed in the order they are listed in the array:

Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () {
        // Uses first & second Middleware
    });

    Route::get('user/profile', function () {
        // Uses first & second Middleware
    });
});

Leave a comment