Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







Laravel Named Routes


05th February 2021 1 min read
Share On     Share On WhatsApp     Share On LinkedIn


I was working on the project and had almost completed it, by then all the sudden my manager told to change the URL prefixes of a few modules of the project. I was searching for routes and replacing them manually. It was a pain in the ass to go and change in all the places.


Then I came across Laravel Named Routes and how it saved me and will save me in future from this kind of situation too.


Named routes allow you to generate URLs without being coupled to the actual URL defined on the route.


Web.php / Api.php


The normal way of adding the routes

Route::get('/auth/login', [AuthController::class, 'login']);


Laravel Named Route

Route::get('/auth/login', [AuthController::class, 'login'])->name('login');


Usage In Blade Template


Instead of

{{ url('/auth/login') }}


You now do the following way with named routes

{{ route('/auth/login') }}

URL Parameters


Old Way

Route::post('/payments/payment-success/{event}', [PaymentController::class, 'store']);


Named Route

Route::post('/payments/payment-success/{event}', [PaymentController::class, 'store'])->name('payment-success');


Usage In Blade


Old Way

{{ url('payments/payment-success/' . $event->id) }}


Named Route

{{ route('payments/payment-success', ['event' => $event->id]) }}

Multiple Parameters


web.php

Route::get('/post/{post}/comment/{comment}', [PostController::class, 'show'])->name('comment.show');


usage

{{ route('comment.show', ['post' => 1, 'comment' => 3]) }}

// http://example.com/post/1/comment/3

GET Parameters


route('post.show', ['post' => 1, 'search' => 'rocket']);

// http://example.com/post/1?search=rocket








Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing