Skip to main content

Defining Routes and Route Parameters

5/28
Chapter 2 Routing, Controllers, and Middleware

Defining Routes and Route Parameters

18 min read Lesson 5 / 28

The Laravel Routing System

Routes map URLs to controller actions. Laravel's routing is expressive, powerful, and central to every application.

Basic Route Definitions

// routes/web.php
use App\Http\Controllers\PostController;

// Closure route (quick prototyping)
Route::get('/welcome', fn () => view('welcome'));

// Controller routes
Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');
Route::post('/posts', [PostController::class, 'store'])->name('posts.store');

Route Parameters

// Required parameter
Route::get('/users/{id}', function (int $id) {
    return "User: {$id}";
});

// Optional parameter
Route::get('/posts/{slug?}', function (?string $slug = null) {
    return $slug ? "Post: {$slug}" : 'All posts';
});

// Constrained parameter
Route::get('/posts/{id}', [PostController::class, 'show'])
    ->whereNumber('id');

Route::get('/users/{name}', [UserController::class, 'show'])
    ->whereAlpha('name');

Route Groups

// Prefix and middleware
Route::prefix('admin')
    ->middleware(['auth', 'admin'])
    ->name('admin.')
    ->group(function () {
        Route::get('/dashboard', [AdminController::class, 'dashboard'])
            ->name('dashboard');
        Route::resource('/posts', AdminPostController::class);
    });

Resource Routes

A single line generates all 7 RESTful routes:

Route::resource('posts', PostController::class);

// Generates:
// GET    /posts           -> index
// GET    /posts/create    -> create
// POST   /posts           -> store
// GET    /posts/{post}    -> show
// GET    /posts/{post}/edit -> edit
// PUT    /posts/{post}    -> update
// DELETE /posts/{post}    -> destroy

Named Routes

Always name your routes for maintainable URLs:

// In Blade
<a href="{{ route('posts.show', $post) }}">{{ $post->title }}</a>

// In controllers
return redirect()->route('posts.index');