Mastering Laravel Routing – Part 6

aravel Laravel Views & Blade Templates – Beginner’s Guide

Advanced Laravel Routing Tutorial

In addition to basic routes, Laravel provides advanced features like fallback routes, rate limiting, method spoofing, CORS, and route caching to make your app more powerful and secure. Let’s explore them one by one.


Fallback Routes

A fallback route handles requests when no other route matches (like a custom 404 page).

Route::fallback(function () {
    return response()->view('errors.404', [], 404);
});

Usually defined in routes/web.php.
Inherits the web middleware by default.


Rate Limiting

Laravel helps prevent abuse by limiting the number of requests per user/IP.

Defining Rate Limiters (AppServiceProvider.php):

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

public function boot(): void
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });
}

Custom Response on Limit Exceeded:

RateLimiter::for('global', function (Request $request) {
    return Limit::perMinute(1000)->response(function ($request, $headers) {
        return response('Too many requests. Try later.', 429, $headers);
    });
});

VIP Users Example:

RateLimiter::for('uploads', function (Request $request) {
    return $request->user()->vipCustomer()
        ? Limit::none()
        : Limit::perMinute(100);
});

Segmenting by User or IP:

RateLimiter::for('uploads', function (Request $request) {
    return $request->user()
        ? Limit::perMinute(100)->by($request->user()->id)
        : Limit::perMinute(10)->by($request->ip());
});

Multiple Rate Limits:

RateLimiter::for('login', function (Request $request) {
    return [
        Limit::perMinute(500),
        Limit::perMinute(3)->by($request->input('email')),
    ];
});

Attaching to Routes:

Route::middleware(['throttle:uploads'])->group(function () {
    Route::post('/audio', fn() => 'Uploaded Audio');
    Route::post('/video', fn() => 'Uploaded Video');
});

Redis for Rate Limiting:

If using Redis cache:

->withMiddleware(function ($middleware) {
    $middleware->throttleWithRedis();
});

Form Method Spoofing

HTML forms only support GET and POST. To use PUT, PATCH, or DELETE, use _method.

<form action="/example" method="POST">
    @method('PUT')
    @csrf
</form>

Accessing the Current Route

You can inspect the current route at runtime:

use Illuminate\Support\Facades\Route;

$route = Route::current();          // Full route object
$name = Route::currentRouteName();  // Route name
$action = Route::currentRouteAction(); // Controller method

Cross-Origin Resource Sharing (CORS)

Laravel automatically handles CORS using the HandleCors middleware.

To customize:

php artisan config:publish cors

A config/cors.php file will be created for you.
Configure allowed origins, methods, and headers there.


Route Caching

To make route registration faster in production, use route caching.

Cache routes:

php artisan route:cache

Clear cache:

php artisan route:clear

Only run this in production (during deployment).


Important

  • Fallback routes → Custom 404 handling.
  • Rate limiting → Control requests per user/IP.
  • Form method spoofing → Support PUT/PATCH/DELETE in forms.
  • Access current route → Useful for debugging.
  • CORS → Manage cross-origin requests.
  • Route caching → Boosts performance in production.