Laravel Basics: Routing and Controllers
Routes and Controllers
2 min read
Last updated 46 minutes ago
Every request enters Laravel through a route, which maps a URL to a controller action.
Defining routes
php
<?php
use App\Http\Controllers\WelcomeController;
use Illuminate\Support\Facades\Route;
Route::get('/', [WelcomeController::class, 'index']);
Route::get('/about', [WelcomeController::class, 'about']);
Route::post('/contact', [ContactController::class, 'store']);
Route verbs map to HTTP methods: get, post, put, patch, delete.
Generating a controller
bash
php artisan make:controller WelcomeController
The controller
php
<?php
namespace App\Http\Controllers;
use Illuminate\View\View;
class WelcomeController extends Controller
{
public function index(): View
{
return view('welcome');
}
}
Controllers keep routes thin and logic testable.
Route parameters
php
Route::get('/users/{id}', [UserController::class, 'show']);
// UserController
public function show(int $id): View
{
return view('users.show', ['id' => $id]);
}
Route model binding
Laravel can inject the model directly using a typed parameter named after the route segment:
php
Route::get('/posts/{post}', [PostController::class, 'show']);
// PostController
public function show(Post $post): View
{
return view('posts.show', ['post' => $post]);
}
✓
Route names
Give routes names with ->name('posts.show') so URLs can be generated with route('posts.show', $post) instead of hard-coding paths.
Naming routes
php
Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');
blade
<a href="{{ route('posts.show', $post) }}">Read more</a>
Advertisement