Laravel Route Names: How to Check If You're in the Right Place

Laravel Route Names: How to Check If You're in the Right Place

Ever needed to know if you're on a specific route in your Laravel app? The named method is your new best friend! Let's dive into how this nifty little feature can make your route handling smoother.

What's the named Method?

The named method lets you check if the current request matches a specific named route. It's like asking your app, "Hey, are we on the 'profile' page right now?"

Basic Usage

Here's how you might use it in a middleware:

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

public function handle(Request $request, Closure $next): Response
{
    if ($request->route()->named('profile')) {
        // We're on the profile route!
        // Do something cool here
    }

    return $next($request);
}

Real-World Example: Custom Analytics Middleware

Let's say you want to track visits to specific pages in your app. Here's how you might do it:

use Closure;
use Illuminate\Http\Request;
use App\Services\AnalyticsService;

class TrackPageVisits
{
    protected $analytics;

    public function __construct(AnalyticsService $analytics)
    {
        $this->analytics = $analytics;
    }

    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        if ($request->route()->named('home')) {
            $this->analytics->trackHomePageVisit();
        } elseif ($request->route()->named('products.*')) {
            $this->analytics->trackProductPageVisit();
        }

        return $response;
    }
}

In this example:

  • We check if we're on the home page
  • We also check if we're on any product-related page (using a wildcard)
  • We track these visits separately

You could then apply this middleware to your routes:

Route::get('/', [HomeController::class, 'index'])->name('home');
Route::get('/products', [ProductController::class, 'index'])->name('products.index');
Route::get('/products/{id}', [ProductController::class, 'show'])->name('products.show');

Route::middleware(TrackPageVisits::class)->group(function () {
    // Your routes here
});

By using the named method, you're making your route-specific logic more flexible and easier to maintain. It's a small feature that can make a big difference in how you structure your Laravel applications!

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter. It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe