Controllers
Closures are great for quick routes, but real applications need structure. Controllers organize your logic into reusable classes. They act as the glue between your routes and your business logic.
Trust me, once you start using controllers, your code becomes so much easier to test and maintain.
Creating a Controller
Laravel gives you a simple artisan command to generate a controller:
php artisan make:controller PostController
This creates a new controller file at app/Http/Controllers/PostController.php with a basic class structure. You can also generate it with a resource method right away:
php artisan make:controller PostController --resource
The --resource flag adds all seven RESTful methods to your controller automatically.
Controller Methods and Routing
Each public method in your controller can be mapped to a route. Here's how you define routes that point to controller methods:
use App\Http\Controllers\PostController;
Route::get('/posts', [PostController::class, 'index']);
Route::get('/posts/{id}', [PostController::class, 'show']);
Route::post('/posts', [PostController::class, 'store']);
Route::put('/posts/{id}', [PostController::class, 'update']);
Route::delete('/posts/{id}', [PostController::class, 'destroy']);
And here's what the controller looks like:
class PostController extends Controller
{
public function index()
{
return view('posts.index');
}
public function show($id)
{
return view('posts.show', compact('id'));
}
}
Dependency Injection
Laravel's container automatically resolves class dependencies. You can type-hint anything in your controller methods and Laravel will inject it:
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required|max:255',
'body' => 'required',
]);
Post::create($validated);
return redirect('/posts');
}
}
The Request object is injected automatically. You can also inject models, services, or any other class. Laravel handles the instantiation for you.