What is Laravel Blade Components
There might have a lot of people ask, what is laravel blade component.
--
Blade components are a subset of blade template that allow you to create new custom, reusable, encapsulated PHP and HTML.
For example you may want to create a layout to be used in many of your application pages. So you build your layout as a component and can reused the component wherever you want.
When created, component can be call with same syntax as any html tag:
<x-layout>
<x-slot>
</x-slot>
</x-layout>
Class based component
Class based component is compose of a php file that encapsulate component logic and a template file.
To create a class based component you can use the Artisan command make:component
php artisan make:component Layout
This command will create two files:
app\View\Components\Layout.php
resources\views\components\layout.blade.php
The Layout.php file is a class that inherits from Component
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class Layout extends Component
{
public function __construct()
{
//
}
public function render()
{
return view('components.layout');
}
}
the layout.blade.php template file is an empty container:
<div>
<!-- Very little is needed to make a happy life. - Marcus Antoninus -->
</div>
Let’s do an example:
When the component will be created you can call your new component by using the x-name syntax:
<x-layout :title="$title"/>
The x- is a convention that tell Laravel to render the specified component name.
The “:” prefix in :message tell Laravel that the content of the props will be bind to a php expression/variables.
When you append the x- before the component name, Laravel know where to look to find your component.
You can retreived those value in the component class file: