Laravel Tutorials

Laravel Request Content Type Inspection Methods

Published
Laravel Request Content Type Inspection Methods image

Laravel provides robust tools for examining client content type preferences through the Accept header. These methods enable sophisticated content negotiation strategies in your applications.

Laravel offers two key methods for content type inspection:

$allTypes = $request->getAcceptableContentTypes();

$canHandle = $request->accepts(['application/json', 'text/html']);

The first method returns all accepted content types, while the second checks if the request accepts any from your specified list.

class ProductController extends Controller
{
    public function catalog(Request $request)
    {
        $products = Product::with('category')->paginate(20);
        $acceptedTypes = $request->getAcceptableContentTypes();
        
        if ($request->accepts(['application/json'])) {
            return response()->json([
                'products' => $products->items(),
                'pagination' => [
                    'current_page' => $products->currentPage(),
                    'total_pages' => $products->lastPage(),
                    'per_page' => $products->perPage()
                ]
            ]);
        }
        
        if ($request->accepts(['application/xml'])) {
            return response()
                ->view('products.xml', compact('products'))
                ->header('Content-Type', 'application/xml');
        }
        
        if ($request->accepts(['text/csv'])) {
            $csvData = $this->generateProductCsv($products);
            return response($csvData)
                ->header('Content-Type', 'text/csv')
                ->header('Content-Disposition', 'attachment; filename="products.csv"');
        }
        
        return view('products.catalog', compact('products'));
    }
    
    public function details(Request $request, Product $product)
    {
        $supportedFormats = ['application/json', 'text/html', 'application/pdf'];
        
        if (!$request->accepts($supportedFormats)) {
            return response()->json([
                'error' => 'Unsupported content type',
                'supported' => $supportedFormats
            ], 406);
        }
        
        if ($request->accepts(['application/json'])) {
            return response()->json([
                'product' => $product->load(['reviews', 'specifications']),
                'related_products' => $product->getRelatedProducts(5),
                'average_rating' => $product->reviews->avg('rating')
            ]);
        }
        
        if ($request->accepts(['application/pdf'])) {
            $pdf = $this->generateProductPdf($product);
            return response($pdf)
                ->header('Content-Type', 'application/pdf')
                ->header('Content-Disposition', 'inline; filename="product-' . $product->id . '.pdf"');
        }
        
        return view('products.details', compact('product'));
    }
    
    private function generateProductCsv($products)
    {
        $output = "ID,Name,Price,Category,Stock\n";
        
        foreach ($products as $product) {
            $output .= sprintf(
                "%d,%s,%.2f,%s,%d\n",
                $product->id,
                $product->name,
                $product->price,
                $product->category->name,
                $product->stock_quantity
            );
        }
        
        return $output;
    }
    
    private function generateProductPdf(Product $product)
    {
        $pdf = new ProductPdfGenerator();
        return $pdf->generate($product);
    }
}

These content inspection methods enable dynamic response formatting based on client capabilities, creating more versatile and user-friendly applications.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43 image

JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43

Read article
Durable Workflow: Long-Running Workflows for Laravel image

Durable Workflow: Long-Running Workflows for Laravel

Read article
Session Replay for Laravel: Self-Hosted Browser Recordings image

Session Replay for Laravel: Self-Hosted Browser Recordings

Read article
Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures image

Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures

Read article
Laravel Read Replicas: Check if a Replica Has Caught Up image

Laravel Read Replicas: Check if a Replica Has Caught Up

Read article
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article