How to Use Laravel 7 New Blade Components Feature

According to Laravel, “components and slots provide similar benefits to sections and layouts; however, some may find the mental model of components and slots easier to understand. There are two approaches to writing components: class based components and anonymous components.”

Let’s use blade components:

Table of Contents

  1. Create a Component
  2. Render Component
  3. Pass Data to Component
  4. Auto Discovery

Create a Component

The make:component command will place the component in the App\View\Components directory. Run this command to create a component named Alert:

php artisan make:component Alert

This command will create two files:

  • app\View\Components\Alert.php
  • resources\views\components\alert.blade.php

Open open the alert.blade.php and modify like this:

alert.blade.php
<div>
    <h3>This is Alert Component</h3>
</div>

Render Component

We can easily render component in blade file. The syntax:

<x-alert/>

x- followed by the kebab case name of component class. Now let’s render in a blade file:

<div class="content">
    <div class="title m-b-md">
        Laravel
    </div>

    <!-- alert component -->
    <x-alert />

</div>

Pass Data to Component

It’s similar to Vue.js’s props. We can pass data to component using HTML attribute. We’re going to pass type and message data to the alert component.

Modify Alert.php like this:

Alert.php
class Alert extends Component
{
    public $type, $message;

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

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view('components.alert');
    }
}

Then modify alert.blade.php:

alert.blade.php
<div class="alert alert-{{$type}}">
    <h3>{{$message}}</h3>
</div>

Now render the component in blade like:

<!-- hardcoded values -->
<x-alert type="success" message="Successfully Stored"/>

<!-- variables -->
<x-alert :type="$type" :message="$message"/>

Auto Discovery

Components are automatically discovered by Laravel in app/View/Components and resources/views/components directories.

We can add nested components too. Example:

The nested component: App\View\Components\Alerts\Success.php

Use in blade file like:

<x-alerts.success/>

 To indicate directory nesting, we have to use . notation.

That’s all. Thanks for reading.