Improved Laravel Routes Tips for Laravel 8.x

Improved Laravel Routes Tips for Laravel 8.x

What are Routes ?

The route is a way of creating a request URL for your application. These urls do not have to map to specific files on a website. The best thing about these URLs is that they are both human-readable and SEO-friendly. In Laravel 5.5, routes are created inside the routes folder. Routes for the website are created on the web.

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[email protected]');
Route::get('register', '[email protected]');

Route::group(['middleware' => 'auth'], function() {
Route::get('edit', '[email protected]');
});
});

Wildcard subdomains

You can create route group by dynamic subdomain name, and pass its value to every route.

Route::domain('{username}.workspace.com')->group(function () {
Route::get('user/{id}', function ($username, $id) {
//
});
});

What’s behind the routes?

If you use Laravel UI package, you likely want to know what routes are actually behind Auth::routes()?

You can check the file /vendor/laravel/ui/src/AuthRouteMethods.php.

public function auth()
{
return function ($options = []) {
// Authentication Routes...
$this->get('login', 'Auth\[email protected]')->name('login');
$this->post('login', 'Auth\[email protected]');
$this->post('logout', 'Auth\[email protected]')->name('logout');
// Registration Routes...
if ($options['register'] ?? true) {
$this->get('register', 'Auth\[email protected]')->name('register');
$this->post('register', 'Auth\[email protected]');
}
// Password Reset Routes...
if ($options['reset'] ?? true) {
$this->resetPassword();
}
// Password Confirmation Routes...
if ($options['confirm'] ?? class_exists($this->prependGroupNamespace('Auth\ConfirmPasswordController'))) {
$this->confirmPassword();
}
// Email Verification Routes...
if ($options['verify'] ?? false) {
$this->emailVerification();
}
};
}

The default use of that function is simply this:

Auth::routes(); // no parameters

But you can provide parameters to enable or disable certain routes:

Auth::routes([
'login' => true,
'logout' => true,
'register' => true,
'reset' => true, // for resetting passwords
'confirm' => false, // for additional password confirmations
'verify' => false, // for email verification
]);

Route Model Binding: You can 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', '[email protected]');

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']);

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', '[email protected]');
Route::resource('tasks', 'Admin\TasksController');
});

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

Route Parameters Validation with RegExp

We can validate parameters directly in the route, with the “where” parameter. A pretty typical case is to prefix your routes by language locale, like fr/blog and en/article/333. How do we ensure that those two first letters are not used for some other than language?

routes/web.php:

Route::group([
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']
], function () {
Route::get('/', '[email protected]');
Route::get('article/{id}', '[email protected]');
});

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 () {
//
});
});

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

Separate Routes by Files

If you have a set of routes related to a certain “section”, you may separate them in a special routes/XXXXX.php file, and just include it in routes/web.php

Example with routes/auth.php in Laravel Breeze by Taylor Otwell himself:

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

Then, in routes/auth.php:

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

But you should use this include() only when that separate route file has the same settings for prefix/middlewares, otherwise it’s better to group them in app/Providers/RouteServiceProvider:

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

Translate Resource Verbs

If you use resource controllers, but want to change URL verbs to non-English for SEO purposes, so instead of /create you want Spanish /crear, you can configure it by using Route::resourceVerbs() method in App\Providers\RouteServiceProvider:

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

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 the Laravel project may be different.

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

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.

More Readable Route List

Have you ever run “php artisan route:list” and then realized that the list takes too much space and hard to read?

Here’s the solution: php artisan route:list --compact

Then it shows 3 columns instead of 6 columns: shows only Method / URI / Action.

+----------+---------------------------------+-------------------------------------------------------------------------+
| Method   | URI                             | Action                                                                  |
+----------+---------------------------------+-------------------------------------------------------------------------+
| GET|HEAD | /                               | Closure                                                                 |
| GET|HEAD | api/user                        | Closure                                                                 |
| POST     | confirm-password                | App\Http\Controllers\Auth\[email protected]           |
| GET|HEAD | confirm-password                | App\Http\Controllers\Auth\[email protected]            |
| GET|HEAD | dashboard                       | Closure                                                                 |
| POST     | email/verification-notification | App\Http\Controllers\Auth\[email protected] |
| POST     | forgot-password                 | App\Http\Controllers\Auth\[email protected]             |
| GET|HEAD | forgot-password                 | App\Http\Controllers\Auth\[email protected]            |
| POST     | login                           | App\Http\Controllers\Auth\[email protected]          |
| GET|HEAD | login                           | App\Http\Controllers\Auth\[email protected]         |
| POST     | logout                          | App\Http\Controllers\Auth\[email protected]        |
| POST     | register                        | App\Http\Controllers\Auth\[email protected]                |
| GET|HEAD | register                        | App\Http\Controllers\Auth\[email protected]               |
| POST     | reset-password                  | App\Http\Controllers\Auth\[email protected]                   |
| GET|HEAD | reset-password/{token}          | App\Http\Controllers\Auth\[email protected]                  |
| GET|HEAD | verify-email                    | App\Http\Controllers\Auth\[email protected]__invoke    |
| GET|HEAD | verify-email/{id}/{hash}        | App\Http\Controllers\Auth\[email protected]__invoke                |
+----------+---------------------------------+-------------------------------------------------------------------------+

You can also specify the exact columns you want:

php artisan route:list --columns=Method,URI,Name

+----------+---------------------------------+---------------------+
| Method   | URI                             | Name                |
+----------+---------------------------------+---------------------+
| GET|HEAD | /                               |                     |
| GET|HEAD | api/user                        |                     |
| POST     | confirm-password                |                     |
| GET|HEAD | confirm-password                | password.confirm    |
| GET|HEAD | dashboard                       | dashboard           |
| POST     | email/verification-notification | verification.send   |
| POST     | forgot-password                 | password.email      |
| GET|HEAD | forgot-password                 | password.request    |
| POST     | login                           |                     |
| GET|HEAD | login                           | login               |
| POST     | logout                          | logout              |
| POST     | register                        |                     |
| GET|HEAD | register                        | register            |
| POST     | reset-password                  | password.update     |
| GET|HEAD | reset-password/{token}          | password.reset      |
| GET|HEAD | verify-email                    | verification.notice |
| GET|HEAD | verify-email/{id}/{hash}        | verification.verify |
+----------+---------------------------------+---------------------+

Eager load relationship

If you use Route Model Binding and think you can’t use Eager Loading for relationships, think again.
So you use Route Model Binding

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

But you have a belongsTo relationship, and cannot use $product->with(‘category’) eager loading?
You actually can! Load the relationship with ->load()

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

Localizing Resource URIs

If you use resource controllers but want to change URL verbs to non-English, so instead of /create you want Spanish /crear, you can configure it with Route::resourceVerbs() method.

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

Resource Controllers naming

In Resource Controllers, in routes/web.php you can specify ->names() parameter, so the URL prefix and the route name prefix may be different.
This will generate URLs like /p/p/{id}/p/{id}/edit etc. But you would call them:

  • route(‘products.index)
  • route(‘products.create)
  • etc
Route::middleware('auth:api', 'throttle:rate_limit,1')->group(function () {
Route::get('/user', function () {
//
});
});

Easily highlight your navbar menus

Use Route::is('route-name') to easily highlight your navbar menus

<ul>
<li @if(Route::is('home')) class="active" @endif>
<a href="/">Home</a>
</li>
<li @if(Route::is('contact-us')) class="active" @endif>
<a href="/contact-us">Contact us</a>
</li>
</ul>

Generate absolute path using route() helper

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

Override the route binding resolver for each of your models

You can override the route binding resolver for each of your models. In this example, I have no control over the @ sign in the URL, so using the resolveRouteBinding method, I’m able to remove the @ sign and resolve the model.

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

If you need public URL but you want them to be secured

If you need public URLs but you want them to be secured, use Laravel signed URL

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

Using Gate in middleware method

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

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

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

Simple route with arrow function

You can use php arrow function in routing, without having to use anonymous function.

To do this, you can use fn() =>, it looks easier.

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

Route view

You can use Route::view($uri , $bladePage) to return a view directly, without having to use controller function.

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

I hope This will help you.

5 1 vote
Article Rating

Please click on advertisment 🙏,helps to maintain website cost
Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x