@markdown# Route group within a groupIn Routes, you can create a group within a group, assigning a certain middleware only to some URLs in the "parent" group.```phpRoute::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'); });});```### Wildcard subdomainsYou can create route group by dynamic subdomain name, and pass its value to every route.```phpRoute::domain('{username}.workspace.com')->group(function () { Route::get('user/{id}', function ($username, $id) { // });});```### What's behind the routes?If you use [Laravel UI package](https://github.com/laravel/ui), you likely want to know what routes are actually behind `Auth::routes()`?You can check the file `/vendor/laravel/ui/src/AuthRouteMethods.php`.```phppublic function auth(){ return function ($options = []) { // Authentication Routes... $this->get('login', 'Auth\LoginController@showLoginForm')->name('login'); $this->post('login', 'Auth\LoginController@login'); $this->post('logout', 'Auth\LoginController@logout')->name('logout'); // Registration Routes... if ($options['register'] ?? true) { $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register'); $this->post('register', 'Auth\RegisterController@register'); } // 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:```phpAuth::routes(); // no parameters```But you can provide parameters to enable or disable certain routes:```phpAuth::routes([ 'login' => true, 'logout' => true, 'register' => true, 'reset' => true, // for resetting passwords 'confirm' => false, // for additional password confirmations 'verify' => false, // for email verification]);```Tip is based on [suggestion](https://github.com/LaravelDaily/laravel-tips/pull/57) by [MimisK13](https://github.com/MimisK13)### Route Model Binding: You can define a keyYou 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:```phppublic function getRouteKeyName() { return 'username';}```### Quickly Navigate from Routes file to ControllerThis thing was optional before Laravel 8, and became a standard main syntax of routing in Laravel 8.Instead of routing like this:```phpRoute::get('page', 'PageController@action');```You can specify the Controller as a class:```phpRoute::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 top of Routes file:```phpuse App\Http\Controllers\PageController;// Then:Route::get('page', [PageController::class, 'action']);```### Route Fallback: When no Other Route is MatchedIf you want to specify additional logic for not-found routes, instead of just throwing default 404 page, you may create a special Route for that, at the very end of your Routes file.```phpRoute::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?';});```### Route Parameters Validation with RegExpWe can validate parameters directly in the route, with “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`:```phpRoute::group([ 'prefix' => '{locale}', 'where' => ['locale' => '[a-zA-Z]{2}']], function () { Route::get('/', 'HomeController@index'); Route::get('article/{id}', 'ArticleController@show');});```### Rate Limiting: Global and for Guests/UsersYou can limit some URL to be called a maximum of 60 times per minute, with `throttle:60,1`:```phpRoute::middleware('auth:api', 'throttle:60,1')->group(function () { Route::get('/user', function () { // });});```But also, you can do it separately for public and for logged-in users:```php// maximum of 10 requests for guests, 60 for authenticated usersRoute::middleware('throttle:10|60,1')->group(function () { //});```Also, you can have a DB field users.rate_limit and limit the amount for specific user:```phpRoute::middleware('auth:api', 'throttle:rate_limit,1')->group(function () { Route::get('/user', function () { // });});```### Query string parameters to RoutesIf 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.```phpRoute::get('user/{id}/profile', function ($id) { //})->name('profile');$url = route('profile', ['id' => 1, 'photos' => 'yes']); // Result: /user/1/profile?photos=yes```### Separate Routes by FilesIf 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](https://github.com/laravel/breeze/blob/1.x/stubs/routes/web.php) by Taylor Otwell himself:```phpRoute::get('/', function () { return view('welcome');});Route::get('/dashboard', function () { return view('dashboard');})->middleware(['auth'])->name('dashboard');require __DIR__.'/auth.php';```Then, in `routes/auth.php`:```phpuse App\Http\Controllers\Auth\AuthenticatedSessionController;use App\Http\Controllers\Auth\RegisteredUserController;// ... more controllersuse Illuminate\Support\Facades\Route;Route::get('/register', [RegisteredUserController::class, 'create']) ->middleware('guest') ->name('register');Route::post('/register', [RegisteredUserController::class, 'store']) ->middleware('guest');// ... A dozen more routes```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`:```phppublic function boot(){ $this->configureRateLimiting(); $this->routes(function () { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); // ... Your routes file listed next here });}```### Translate Resource VerbsIf 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`:```phppublic function boot(){ Route::resourceVerbs([ 'create' => 'crear', 'edit' => 'editar', ]); // ...}```### Custom Resource Route NamesWhen 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.```phpRoute::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.### More Readable Route ListHave 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\ConfirmablePasswordController@store || GET|HEAD | confirm-password | App\Http\Controllers\Auth\ConfirmablePasswordController@show || GET|HEAD | dashboard | Closure || POST | email/verification-notification | App\Http\Controllers\Auth\EmailVerificationNotificationController@store || POST | forgot-password | App\Http\Controllers\Auth\PasswordResetLinkController@store || GET|HEAD | forgot-password | App\Http\Controllers\Auth\PasswordResetLinkController@create || POST | login | App\Http\Controllers\Auth\AuthenticatedSessionController@store || GET|HEAD | login | App\Http\Controllers\Auth\AuthenticatedSessionController@create || POST | logout | App\Http\Controllers\Auth\AuthenticatedSessionController@destroy || POST | register | App\Http\Controllers\Auth\RegisteredUserController@store || GET|HEAD | register | App\Http\Controllers\Auth\RegisteredUserController@create || POST | reset-password | App\Http\Controllers\Auth\NewPasswordController@store || GET|HEAD | reset-password/{token} | App\Http\Controllers\Auth\NewPasswordController@create || GET|HEAD | verify-email | App\Http\Controllers\Auth\EmailVerificationPromptController@__invoke || GET|HEAD | verify-email/{id}/{hash} | App\Http\Controllers\Auth\VerifyEmailController@__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 relationshipIf you use Route Model Binding and think you can't use Eager Loading for relationships, think again.
So you use Route Model Binding```phppublic function show(Product $product) { //}```But you have a belongsTo relationship, and cannot use $product->with('category') eager loading?
You actually can! Load the relationship with `->load()````phppublic function show(Product $product) { $product->load('category'); //}```### Localizing Resource URIsIf 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.```phppublic function boot(){ Route::resourceVerbs([ 'create' => 'crear', 'edit' => 'editar', ]); //}```### Resource Controllers namingIn 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```phpRoute::resource('p', \App\Http\Controllers\ProductController::class)->names('products');```### Easily highlight your navbar menusUse `Route::is('route-name')` to easily highlight your navbar menus```html```Tip given by [@anwar_nairi](https://twitter.com/anwar_nairi/status/1443893957507747849)### Generate absolute path using route() helper```phproute('page.show', $page->id);// http://laravel.test/pages/1route('page.show', $page->id, false);// /pages/1```Tip given by [@oliverds_](https://twitter.com/oliverds_/status/1445796035742240770)### Override the route binding resolver for each of your modelsYou 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// RouteRoute::get('{product:slug}', Controller::class);// Requesthttps://nodejs.pub/@unlock/hello-world// Product Modelpublic function resolveRouteBinding($value, $field = null){ $value = str_replace('@', '', $value); return parent::resolveRouteBinding($value, $field);}```Tip given by [@Philo01](https://twitter.com/Philo01/status/1447539300397195269)### If you need public URL but you want them to be securedIf you need public URL but you want them to be secured, use Laravel signed URL```phpclass AccountController extends Controller{ public function destroy(Request $request) { $confirmDeleteUrl = URL::signedRoute('confirm-destroy', [ $user => $request->user() ]); // Send link by email... } public function confirmDestroy(Request $request, User $user) { if (! $request->hasValidSignature()) { abort(403); } // User confirmed by clikcing on the email $user->delete(); return redirect()->route('home'); }}```Tip given by [@anwar_nairi](https://twitter.com/anwar_nairi/status/1448239591467589633)### Using Gate in middleware methodYou 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.```phpRoute::put('/post/{post}', function (Post $post) { // The current user may update the post...})->middleware('can:update,post');```### 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// Instead ofRoute::get('/example', function () { return User::all();});// You canRoute::get('/example', fn () => User::all());```### Route view You can use `Route::view($uri , $bladePage)` to return a view directly, without having to use controller function.```php//this will return home.blade.php viewRoute::view('/home', 'home');```### Route directory instead of route fileYou can create a */routes/web/* directory and only fill */routes/web.php* with:```phpforeach(glob(dirname(__FILE__).'/web/*', GLOB_NOSORT) as $route_file){ include $route_file;}```Now every file inside */routes/web/* act as a web router file and you can organize your routes into diferent files.### Route resources groupingIf your routes have a lot of resource controllers, you can group them and call one Route::resources() instead of many single Route::resource() statements.```phpRoute::resources([ 'photos' => PhotoController::class, 'posts' => PostController::class,]);```### Custom route bindingsDid you know you can define custom route bindings in Laravel?
In this example, I need to resolve a portfolio by slug. But the slug is not unique, because multiple users can have a portfolio named 'Foo'
So I define how Laravel should resolve them from a route parameter```phpclass RouteServiceProvider extends ServiceProvider{ public const HOME = '/dashboard'; public function boot() { Route::bind('portfolio', function (string $slug) { return Portfolio::query() ->whereBelongsto(request()->user()) ->whereSlug($slug) ->firstOrFail(); }); }}``````phpRoute::get('portfolios/{portfolio}', function (Portfolio $portfolio) { /* * The $portfolio will be the result of the query defined in the RouteServiceProvider */})```Tip given by [@mmartin_joo](https://twitter.com/mmartin_joo/status/1496871240346509312)### Two ways to check the route nameHere are two ways to check the route name in Laravel.```php// #1 Home// #2 Home```Tip given by [@AndrewSavetchuk](https://twitter.com/AndrewSavetchuk/status/1510197418909999109)### Route model binding soft-deleted modelsBy default, when using route model binding will not retrieve models that have been soft-deleted.You can change that behavior by using `withTrashed` in your route.```phpRoute::get('/posts/{post}', function (Post $post) { return $post;})->withTrashed();```Tip given by [@cosmeescobedo](https://twitter.com/cosmeescobedo/status/1511154599255703553)### Retrieve the URL without query parametersIf for some reason, your URL is having query parameters, you can retrieve the URL without query parameters using the `fullUrlWithoutQuery` method of request like so.```php// Original URL: https://www.amitmerchant.com?search=laravel&lang=en&sort=desc$urlWithQUeryString = $request->fullUrlWithoutQuery([ 'lang', 'sort']);echo $urlWithQUeryString;// Outputs: https://www.amitmerchant.com?search=laravel```Tip given by [@amit_merchant](https://twitter.com/amit_merchant/status/1510867527962066944)### Customizing Missing Model Behavior in route model bindingsBy default, Laravel throws a 404 error when it can't bind the model, but you can change that behavior by passing a closure to the missing method.```phpRoute::get('/users/{user}', [UsersController::class, 'show']) ->missing(function ($parameters) { return Redirect::route('users.index'); });```Tip given by [@cosmeescobedo](https://twitter.com/cosmeescobedo/status/1511322007576608769)### Exclude middleware from a routeYou can exclude middleware at the route level in Laravel using the withoutMiddleware method.```phpRoute::post('/some/route', SomeController::class) ->withoutMiddleware([VerifyCsrfToken::class]);```Tip given by [@alexjgarrett](https://twitter.com/alexjgarrett/status/1512529798790320129)### Controller groupsInstead of using the controller in each route, consider using a route controller group. Added to Laravel since v8.80```php// BeforeRoute::get('users', [UserController::class, 'index']);Route::post('users', [UserController::class, 'store']);Route::get('users/{user}', [UserController::class, 'show']);Route::get('users/{user}/ban', [UserController::class, 'ban']);// AfterRoute::controller(UsersController::class)->group(function () { Route::get('users', 'index'); Route::post('users', 'store'); Route::get('users/{user}', 'show'); Route::get('users/{user}/ban', 'ban');});```Tip given by [@justsanjit](https://twitter.com/justsanjit/status/1514943541612527616)@endmarkdown
We use cookies to improve your experience and to help us understand how you use our site. By using this site, you accept our use of cookies. Cookie Info x