Quick Guide For Laravel Routes

1. The Default Route Files

  • The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection.
  • The routes in routes/api.php are stateless and are assigned the api middleware group.

2. Defining Routes

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use Illuminate\Http\Request;

Route::get('/greeting', function () {
    return 'Hello World';
});

// Required Parameter
Route::get('/user/{id}', function (string $id) {
    return 'User '.$id;
});

Route::get('/posts/{post}/comments/{comment}', function (string $postId, string $commentId) {
    // ...
});

// Parameters & Dependency Injection
Route::get('/user/{id}', function (Request $request, string $id) {
    return 'User '.$id;
});

// Optional Parameters
Route::get('/user/{name?}', function (?string $name = null) {
    return $name;
});
 
Route::get('/user/{name?}', function (?string $name = 'John') {
    return $name;
});

// Regular Expression Constraints
Route::get('/user/{name}', function (string $name) {
    // ...
})->where('name', '[A-Za-z]+');
 
Route::get('/user/{id}', function (string $id) {
    // ...
})->where('id', '[0-9]+');
 
Route::get('/user/{id}/{name}', function (string $id, string $name) {
    // ...
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

Route::get('/user/{id}/{name}', function (string $id, string $name) {
    // ...
})->whereNumber('id')->whereAlpha('name');
 
Route::get('/user/{name}', function (string $name) {
    // ...
})->whereAlphaNumeric('name');
 
Route::get('/user/{id}', function (string $id) {
    // ...
})->whereUuid('id');
 
Route::get('/user/{id}', function (string $id) {
    //
})->whereUlid('id');
 
Route::get('/category/{category}', function (string $category) {
    // ...
})->whereIn('category', ['movie', 'song', 'painting'])

Route::get('/search/{search}', function (string $search) {
    return $search;
})->where('search', '.*'); // Encoded Forward Slashes

// View Routes
Route::view('/welcome', 'welcome');
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);

// Named Routes
Route::get('/user/profile', function () {
    // ...
})->name('profile');

Route::get(
    '/user/profile',
    [UserProfileController::class, 'show']
)->name('profile');

// Route Groups

// Group Routes by Middleware
Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () {
        // Uses first & second middleware...
    });
    Route::get('/user/profile', function () {
        // Uses first & second middleware...
    });
});

// Group Routes by Controllers
use App\Http\Controllers\OrderController;
 
Route::controller(OrderController::class)->group(function () {
    Route::get('/orders/{id}', 'show');
    Route::post('/orders', 'store');
});

// Group Routes by Controllers
Route::domain('{account}.example.com')->group(function () {
    Route::get('user/{id}', function (string $account, string $id) {
        // ...
    });
});

// Group Routes by Route Prefixes
Route::prefix('admin')->group(function () {
    Route::get('/users', function () {
        // Matches The "/admin/users" URL
    });
});

// Group Routes by Route Name Prefixes
Route::name('admin.')->group(function () {
    Route::get('/users', function () {
        // Route assigned name "admin.users"...
    })->name('users');
});

// Route Model Binding
use App\Models\User;
 
Route::get('/users/{user}', function (User $user) {
    return $user->email;
});

// OR

use App\Http\Controllers\UserController;
use App\Models\User;
 
// Route definition
Route::get('/users/{user}', [UserController::class, 'show']);
 
// Controller method definition
public function show(User $user)
{
    return view('user.profile', ['user' => $user]);
}

//Route Model Binding with Soft Deleted Models
use App\Models\User;
 
Route::get('/users/{user}', function (User $user) {
    return $user->email;
})->withTrashed();


// Customizing The Key
use App\Models\Post;
 
Route::get('/posts/{post:slug}', function (Post $post) {
    return $post;
});

// Custom Keys & Scoping
use App\Models\Post;
use App\Models\User;
 
Route::get('/users/{user}/posts/{post:slug}', function (User $user, Post $post) {
    return $post;
});

Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
    return $post;
})->scopeBindings();

Route::scopeBindings()->group(function () {
    Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
        return $post;
    });
});

Route::get('/users/{user}/posts/{post:slug}', function (User $user, Post $post) {
    return $post;
})->withoutScopedBindings();

//Fallback Routes
Route::fallback(function () {
    // ...
});


3. Available Router Methods

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
Route::match(['get', 'post'], '/', function () {
    // ...
});
Route::any('/', function () {
    // ...
});

4. CSRF Protection

<form method="POST" action="/profile">
    @csrf
    ...
</form>

5. View Routes

Route::view('/welcome', 'welcome');
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);

6. Command to see list of routes

php artisan route:list
php artisan route:list -v // Display the route middleware and middleware group names
php artisan route:list -vv // Expand middleware groups
php artisan route:list --path=api
php artisan route:list --except-vendor
php artisan route:list --only-vendor

7. Global Constraints

// App\Providers\RouteServiceProvider
public function boot(): void
{
    Route::pattern('id', '[0-9]+');
}

Once the pattern has been defined, it is automatically applied to all routes using that parameter name.

8. Defining Rate Limiters

// App\Providers\RouteServiceProvider

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
 
/**
 * Define your route model bindings, pattern filters, and other route configuration.
 */
protected function boot(): void
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });
 
    RateLimiter::for('global', function (Request $request) {
        return Limit::perMinute(1000);
    });
    
    // OR
    
    RateLimiter::for('global', function (Request $request) {
    return Limit::perMinute(1000)->response(function (Request $request, array $headers) {
        return response('Custom response...', 429, $headers);
    });
    
    RateLimiter::for('uploads', function (Request $request) {
    return $request->user()->vipCustomer()
                ? Limit::none()
                : Limit::perMinute(100);
    });
    
    //Segmenting Rate Limits
    RateLimiter::for('uploads', function (Request $request) {
    return $request->user()->vipCustomer()
                ? Limit::none()
                : Limit::perMinute(100)->by($request->ip());
    });
    
    // OR
    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')),
    ];
    });
    
    
});

}

9. Attaching Rate Limiters To Routes

Route::middleware(['throttle:uploads'])->group(function () {
    Route::post('/audio', function () {
        // ...
    });
 
    Route::post('/video', function () {
        // ...
    });
});

10. Form Method Spoofing

<form action="/example" method="POST">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
<form action="/example" method="POST">
    @method('PUT')
    @csrf
</form>

11. Accessing The Current Route

use Illuminate\Support\Facades\Route;
 
$route = Route::current(); // Illuminate\Routing\Route
$name = Route::currentRouteName(); // string
$action = Route::currentRouteAction(); // string

12. Inspecting The Current Route

$request->route()->named('profile') // $request is instance of Request class of laravel

13. Route Caching

php artisan route:cache // cache routes

php artisan route:clear // clear routes cache

Note: This post is related to latest version of Laravel, please check the official documentation for older version of Laravel framework.