Tuesday, March 8, 2022

Laravel Routes Tips for Laravel 8.x

 https://blog.codehunger.in/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.

PHP

Wildcard subdomains

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

PHP

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.

PHP

The default use of that function is simply this:

PHP

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

PHP

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:

PHP

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:

PHP

You can specify the Controller as a class:

PHP

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:

PHP

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.

PHP

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:

PHP

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:

PHP

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

PHP

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

PHP

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.

PHP

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:

PHP

Then, in routes/auth.php:

PHP

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:

PHP

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:

PHP

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.

PHP

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.

PHP

You can also specify the exact columns you want:

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

PHP

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

PHP

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

PHP

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.

PHP

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
PHP

Easily highlight your navbar menus

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

HTML

Generate absolute path using route() helper

PHP

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.

PHP

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

PHP

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.

PHP

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.

PHP

Route view

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

PHP

I hope This will help you.

No comments:

Post a Comment