Blog Detail

08

Nov
Some Useful Laravel Tips & Tricks for Laravel Routing cover image

arrow_back Some Useful Laravel Tips & Tricks for Laravel Routing

Routing in Laravel allows you to route all your application requests to its appropriate controller. The main and primary routes in Laravel acknowledge and accept a URI (Uniform Resource Identifier) along with a closure, given that it should have to be a simple and expressive way of routing. In this blog, I’ll share some tips for laravel routing so you can improve your code quality and usability.

Route group within a group

In Routes, you can create a group within a group, assigning a certain middleware only to some URLs in the parent group.

Route::group(['prefix' => 'account', 'as' => 'account.'], function() {
    Route::get('login', 'AccountController@login');
    Route::get('register', 'AccountController@register');
    
    Route::group(['middleware' => 'auth'], function() {
        Route::get('edit', 'AccountController@edit');
    });
});

Using Gate in middleware method

You can use the gates you specified in App\Providers\AuthServiceProvider in the middleware method.

To do this, you just need to put inside the can: and the names of the necessary gates.

Route::put('/post/{post}', function (Post $post) {
    // The current user may update the post...
})->middleware('can:update,post');

Route Model Binding: Easily define a key

You can do Route model binding like

Route::get(‘api/users/{user}’, function (App\User $user) { … } - but not only by ID field. If you want {user} to be a username field, put this in the model:

public function getRouteKeyName() {
    return 'username';
}

Quickly Navigate from Routes file to Controller

This thing was optional before Laravel 8 and became a standard main syntax of routing in Laravel 8.

Instead of routing like this:

Route::get('page', 'PageController@action');

You can specify the Controller as a class:

Route::get('page', [\App\Http\Controllers\PageController::class, 'action']);

Then you will be able to click on PageController in PhpStorm and navigate directly to Controller, instead of searching for it manually.

Or, to make it shorter, add this to the top of the Routes file:

use App\Http\Controllers\PageController;

// Then:
Route::get('page', [PageController::class, 'action']);

Query string parameters to Routes

If you pass additional parameters to the route, in the array, those key/value pairs will automatically be added to the generated URL’s query string.

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


$url = route('profile', ['id' => 1, 'photos' => 'yes']); // Result: /user/1/profile?photos=yes

Custom Resource Route Names

When using Resource Controllers, in routes/web.php you can specify ->names() parameter, so the URL prefix in the browser and the route name prefix you use all over Laravel project may be different.

Route::resource('p', ProductController::class)->names('products');

So this code above will generate URLs like /p, /p/{id}, /p/{id}/edit, etc. But you would call them in the code by route(‘products.index’), route(‘products.create’), etc.

Rate Limiting: Global and for Guests/Users

You can limit some URLs to be called a maximum of 60 times per minute, with throttle:60,1:

Route::middleware('auth:api', 'throttle:60,1')->group(function () {
    Route::get('/user', function () {
        //
    });
});

But also, you can do it separately for the public and for logged-in users:

// maximum of 10 requests for guests, 60 for authenticated users
Route::middleware('throttle:10|60,1')->group(function () {
    //
});

Also, you can have a DB field users.rate_limit and limit the amount for a specific user:

Route::middleware('auth:api', 'throttle:rate_limit,1')->group(function () {
    Route::get('/user', function () {
        //
    });
});

Route Fallback: When no Other Route is Matched

If you want to specify additional logic for not-found routes, instead of just throwing the default 404 page, you may create a special Route for that, at the very end of your Routes file.

Route::group(['middleware' => ['auth'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
    Route::get('/home', 'HomeController@index');
    Route::resource('tasks', 'Admin\TasksController');
});

// Some more routes....
Route::fallback(function() {
    return 'Hm, why did you land here somehow?';
});

Published at : 08-11-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project