Routing Basics

Routes map a URL and HTTP method to the code that should handle it.

SyntaxRoute::get('/uri', $callback);

Routes live in routes/web.php. Each route ties an HTTP verb and URL to a closure or controller method. The closure's return value becomes the response.

This code needs a full HTTP application to run, so it is shown here for reference.

Example

Example · php
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return 'Welcome home!';
});

Route::get('/about', function () {
    return 'About us';
});

When to use it

  • A marketing team member adds a new /about route in web.php and points it to a static view without touching any controller, getting the page live in minutes.
  • A REST API separates public and authenticated routes into different files (api.php vs web.php) so rate limiting and CSRF middleware apply only where needed.
  • A developer organises related product routes under a Route::prefix('products') group to keep the routes file readable as the application grows.

More examples

Basic GET and POST routes

Defines a view route, a JSON route, and a controller route, showing the three most common routing patterns in a typical Laravel application.

Example · php
use Illuminate\Support\Facades\Route;

// Return a view
Route::get('/', fn() => view('welcome'));

// Return JSON from a closure
Route::get('/ping', fn() => ['status' => 'ok']);

// Handle a form POST
Route::post('/contact', [ContactController::class, 'store']);

Route group with prefix and middleware

Groups three dashboard routes behind the 'auth' middleware and prefixes all URLs with /dashboard to eliminate repetition.

Example · php
Route::middleware('auth')->prefix('dashboard')->group(function () {
    Route::get('/', [DashboardController::class, 'index']);
    Route::get('/analytics', [AnalyticsController::class, 'index']);
    Route::get('/settings', [SettingsController::class, 'index']);
});

Separate web and API routes

Shows how web.php and api.php serve different concerns: web routes use session auth and CSRF, while API routes use token auth and are stateless.

Example · php
// routes/web.php  -- cookie sessions, CSRF
Route::get('/dashboard', [DashboardController::class, 'index'])
    ->middleware('auth');

// routes/api.php  -- stateless, rate-limited, /api/* prefix
Route::get('/users', [UserApiController::class, 'index'])
    ->middleware('auth:sanctum');

Discussion

  • Be the first to comment on this lesson.