SyntaxStudy
Sign Up
Laravel Creating and Using Controllers
Laravel Beginner 1 min read

Creating and Using Controllers

Controllers in Laravel are PHP classes that group related HTTP request-handling logic together. Instead of defining all logic as closures in route files, controllers keep your route files clean and your business logic organized. A controller extends Illuminate\Routing\Controller and its methods correspond to route actions. Laravel's dependency injection container automatically resolves any type-hinted services in controller constructors and methods. You generate a controller with php artisan make:controller PostController. Adding the --resource flag scaffolds all seven resourceful methods. Adding --model=Post connects implicit route model binding so parameters are already typed and documented. Single-action controllers — used for complex, focused actions — implement __invoke() and are referenced in routes as a single class name. Controllers should remain thin. They receive a request, delegate work to services or models, and return a response. Keeping business logic in dedicated service classes or action classes rather than bloating controllers makes code easier to test and reuse. Form requests can be injected to move validation out of the controller body entirely.
Example
<?php
// app/Http/Controllers/PostController.php

namespace App\Http\Controllers;

use App\Http\Requests\StorePostRequest;
use App\Http\Requests\UpdatePostRequest;
use App\Models\Post;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class PostController extends Controller
{
    public function index(): View
    {
        $posts = Post::latest()->paginate(15);
        return view('posts.index', compact('posts'));
    }

    public function create(): View
    {
        return view('posts.create');
    }

    public function store(StorePostRequest $request): RedirectResponse
    {
        $post = Post::create($request->validated());
        return redirect()->route('posts.show', $post)
            ->with('success', 'Post created successfully.');
    }

    public function show(Post $post): View
    {
        return view('posts.show', compact('post'));
    }

    public function edit(Post $post): View
    {
        return view('posts.edit', compact('post'));
    }

    public function update(UpdatePostRequest $request, Post $post): RedirectResponse
    {
        $post->update($request->validated());
        return redirect()->route('posts.show', $post)
            ->with('success', 'Post updated.');
    }

    public function destroy(Post $post): RedirectResponse
    {
        $post->delete();
        return redirect()->route('posts.index')
            ->with('success', 'Post deleted.');
    }
}