Laravel Components: Understanding Blade Components and View Components

February 02, 2023

In Laravel, components are reusable pieces of HTML and/or PHP code that can be used throughout your application. They can be used to build complex UI elements, such as navigation menus, modals, alerts, and more.

There are two types of components in Laravel: Blade components and View components.

Blade Components: Blade components are reusable UI elements defined using Blade templating language. They are created as Blade template files and stored in the resources/views/components directory. Here's an example of a Blade component:

<!-- resources/views/components/alert.blade.php --> 
<div class="alert alert-{{ $type }}"> {{ $slot }} </div>

In the example above, the alert component accepts a $type parameter and a $slot parameter, which allows you to pass data into the component.

Here's an example of how to use the alert component in a Blade template:

<!-- resources/views/welcome.blade.php -->
 <x-alert type="success"> Congratulations! Your account has been created. </x-alert>

In the example above, the x-alert directive is used to render the alert component and pass data to it.

View Components: View components are reusable UI elements defined as classes in PHP. They are created as classes and stored in the app/ViewComponents directory. Here's an example of a View component:

<?php 
namespace App\ViewComponents;

use Illuminate\View\View;

class AlertComponent
{ 
    public $type; 

    public function __construct(string $type) 
    { 
       $this->type = $type; 
    } 

   public function render(View $view) 
   { 
       return $view->make('components.alert', [ 'type' => $this->type, ]); 
   } 
} 

In the example above, the AlertComponent class accepts a $type parameter and has a render method, which returns the view for the component.

Here's an example of how to use the AlertComponent class in a Blade template:

<!-- resources/views/welcome.blade.php --> 
  @component('components.alert', ['type' => 'success']) Congratulations! Your account has been created. @endcomponent 

In the example above, the @component directive is used to render the AlertComponent class and pass data to it.

Both Blade components and View components are powerful tools for creating reusable UI elements in Laravel. They allow you to organize your code, keep your UI elements consistent, and reduce the amount of duplicated code in your application.