Views

Blade Components

Use Blade components for clean, maintainable, and reusable views. Avoid using @extends, @section, and @yield for layout inheritance; instead, use Blade components and slots.

  • Create components in resources/views/components.
  • Use <x-component-name> syntax in Blade files.
  • Pass data to components via attributes and slots.

Example:

<!-- resources/views/components/layout.blade.php -->
<div>
    <header>{{ $header }}</header>
    <main>{{ $slot }}</main>
</div>
<!-- resources/views/users/index.blade.php -->
<x-layout>
    <x-slot name="header">
        <h1>{{ $title }}</h1>
    </x-slot>
    <p>{{ $description }}</p>
</x-layout>

View Composers

Use view composers to inject data into views automatically, keeping controllers clean.

  • Register composers in a service provider or in routes/web.php.
  • Use composers for global data (e.g., user count, notifications).

Example:

View::composer('profile', function ($view) {
    $view->with('count', User::count());
});

Organizing Views

Organize views by feature or domain for maintainability.

resources/views/
    layouts/      # Master layouts
    components/   # Reusable UI components
    users/        # User-related views
    posts/        # Post-related views
  • Use partials for reusable sections (e.g., navigation, footer).
  • Use Blade components for reusable UI elements.
  • Group related views in subdirectories.

Best Practices

  • Use Blade components and slots for DRY, maintainable templates.
  • Avoid using @extends, @section, and @yield for new views.
  • Escape all output to prevent XSS ({{ $variable }}).
  • Use localization for all user-facing text.
  • Document view structure and conventions for new team members.