SyntaxStudy
Sign Up
Laravel Basic Routing with Route Facades
Laravel Beginner 1 min read

Basic Routing with Route Facades

Laravel routing is defined in the routes/ directory. The routes/web.php file handles routes with the web middleware group (sessions, CSRF protection), while routes/api.php handles stateless API routes with the api middleware group. Routes are registered using the Route facade and support all HTTP verbs: GET, POST, PUT, PATCH, DELETE, and OPTIONS. Routes can return views, strings, JSON, or be delegated to controller methods. Route parameters are defined using curly braces and are passed automatically to the closure or controller method. Optional parameters use a trailing question mark and must have a default value in the function signature. Regular expression constraints can be applied with the where() method. Named routes allow generating URLs and redirects without hard-coding URIs. A route is named by chaining ->name('route.name') after its definition. You can then call route('route.name') in Blade templates or redirect()->route('route.name') in controllers. This decouples your code from specific URL structures, making future URL changes painless.
Example
<?php
// routes/web.php

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

// Basic GET route returning a view
Route::get('/', function () {
    return view('welcome');
})->name('home');

// Route with a required parameter
Route::get('/posts/{post}', [PostController::class, 'show'])
    ->name('posts.show')
    ->where('post', '[0-9]+');

// Route with an optional parameter
Route::get('/users/{name?}', function (?string $name = 'Guest') {
    return 'Hello, ' . $name;
})->name('users.greet');

// POST route for form submission
Route::post('/posts', [PostController::class, 'store'])
    ->name('posts.store');

// Redirect route
Route::redirect('/old-blog', '/posts', 301);

// View shortcut route
Route::view('/about', 'pages.about')->name('about');

// Generate a URL from a named route
$url = route('posts.show', ['post' => 42]);
// => http://example.com/posts/42