SyntaxStudy
Sign Up
Laravel Middleware in Controllers and Responses
Laravel Beginner 1 min read

Middleware in Controllers and Responses

Middleware can be attached to controller actions directly from within the controller constructor using $this->middleware(). This is convenient when middleware applies only to certain actions. The except() and only() methods limit middleware to specific controller methods. Since Laravel 10, controller middleware is applied using the static middleware() method that returns a MiddlewareConfig object. Laravel controllers can return a variety of response types. The response() helper creates an HTTP response with custom status codes and headers. JSON responses are returned with response()->json(), which automatically sets the Content-Type header. File downloads use response()->download(), while streaming responses use response()->stream(). Redirects can target routes, URLs, previous pages, or named routes with flashed session data. Resource responses wrap a model or collection in a transformation layer before sending JSON to the client, using Laravel API resources. This gives you full control over what data is exposed and in what shape. Calling $this->authorize() inside a controller method performs authorization via policies and throws an AuthorizationException (403) if the user lacks permission.
Example
<?php
// app/Http/Controllers/DocumentController.php

namespace App\Http\Controllers;

use App\Models\Document;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;

class DocumentController extends Controller
{
    public function __construct()
    {
        // Apply auth middleware to all except index
        $this->middleware('auth')->except('index');
        // Apply throttle to store
        $this->middleware('throttle:10,1')->only('store');
    }

    public function show(Document $document): JsonResponse
    {
        // Authorize using a policy
        $this->authorize('view', $document);

        return response()->json([
            'data' => $document,
        ], 200, ['X-Custom-Header' => 'value']);
    }

    public function download(Document $document): Response
    {
        $this->authorize('download', $document);

        return response()->download(
            storage_path('app/' . $document->path),
            $document->original_name
        );
    }

    public function destroy(Document $document): JsonResponse
    {
        $this->authorize('delete', $document);
        $document->delete();

        return response()->json(['message' => 'Deleted.'], 200);
    }
}