Laravel Blade Components Tutorial with example - All about components in laravel

By Ved Prakash N | Nov 25, 2023 | Laravel
Share : Whatsapp

https://www.fundaofwebit.com/post/laravel-blade-components-tutorial-with-example-all-about-components-in-laravel

Laravel Blade Components Tutorial with an example - All about components in Laravel 10


In this post, we will learn how to use Laravel Blade Components step by step with an example. We will be seeing how to

  1. Create components
  2. Render the components
  3. Passing Data To Components ( as string and variable )
  4. Component attributes
  5. Slots

For a more detailed explanation, please take a look at the video above.


Create a component in Laravel

There are 2 ways to create a component in laravel. 

  1. Class based Component
  2. Directly create a file as a blade component.
1. Class based Component

Step 1: To create a class based component you can use the Artisan command as follows:

php artisan make:component AlertMessage

This command will create two files:

app\View\Components\AlertMessage.php
resources\views\components\alert-message.blade.php


Step 2: Open The AlertMessage.php class component and it looking like this now:

<?php

namespace App\View\Components;

use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;

class AlertMessage extends Component
{
    /**
     * Create a new component instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        return view('components.alert-message');
    }
}


Step 3: Open the alert-message.blade.php blade component and it looks like this now:

<div>

</div>

Let's add some bootstrap classes to make as an alert box to show messages in the alert-message.blade.php file

<div class="alert alert-success">
    My Alert Message
</div>


Step 4: You can call your new component by using the x-name syntax as follows: 

<x-alert-message />

2. Create a file as blade Component

Create a new Blade component file named notification.blade.php in the resources/views/components directory.

<div class="alert alert-info notification">
    My Noficiation Alert
</div>

Now, use the notification component in your view: in any blade file.

<x-notification />

Let's do an example with the above components. The final goal will be to display a alert message and style that message base on the alert type (error or success). Which is also called as Passing data or message to components.


Passing Data To Components

Passing data to components can be done in 2 ways in laravel.

  1. Class Component
  2. Directly to Blade Component (using @props).
1. Let's start with the "Class Component".

As we have already created the AlertMessage Component above.

Step 1: let's open the blade component file named alert-message.blade.php file "resources/ views/ components/ alert-message.blade.php" and paste the below code:

<div class="alert alert-{{ $type }}">
    {{ $message }}
</div>


Step 2: Let's open the class component file named AlertMessage.php file "app/ View/ Components/ AlertMessage.php" file and paste the below code:

<?php

namespace App\View\Components;

use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;

class AlertMessage extends Component
{
    public $message;
    public string $type;

    /**
     * Create a new component instance.
     */
    public function __construct($message, $type)
    {
        $this->message = $message;
        $this->type = $type;
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        return view('components.alert-message');
    }
}


Step 3: Now, use the alert-message component in your view: ( Eg: example-view.blade.php )
:type and :message are data pass to the component

<x-alert-message :type="$type" :message="$message" />
<x-alert-message type="success" message="My Alert Message Box" />

That's in the Class Component.


2. Let's start with the "Blade Component" 

As we have already created the Notification Blade Component above, we will be using that notification component here.

Step 1: let's open the blade component file named notification.blade.php file "resources/ views/ components/ notification.blade.php" and paste the below code:

@props([
    'type' => 'info',
    'message'
])

<div class="alert alert-{{ $type }} notification">
    {{ $message }}
</div>

Here we are not using any class, so instead of class, we are using props in the blade component to access the data.

Step 2: Now, use the notification component in your view: ( Eg: example-view.blade.php )
:type and :message are data pass to the component

<x-notification type="success" message="Success! Your changes have been saved" />

<x-notification type="warning" message="Error! Something went wrong" />

<x-notification :type="$type" :message="$message" />


Components Attributes

Sometimes you may need to specify additional HTML attributes, such as class that are not part of your component data.

<x-notification type="success" message="Success!" class="mt-4" />

If you want to pass these additional attributes down to the root element of the component template you can use the $attributes variable.

<div {{ $attributes }}>

</div>

If a class attribute already exists in your div you can use $attributes->merge to merge both together.

<div {{ $attributes->merge(['class' => 'alert alert-'.$type.'   notification']) }}>
    {{ $message }}
</div>

you can merge many attributes like below example:

<div>
    <button
        {{
            $attributes->merge([
                'class' => 'alert alert-'.$type.'   notification',
                'type' => 'button'
            ])
        }}
    >
        {{ $message }}
    </button>
</div>


Slots

You will often need to pass additional content to your component via "slots". Component slots are rendered by echoing the $slot variable.

Let's start here with the new example called <label> and pass the content to the component:

Step 1: Create a blade component named label.blade.php in the following directory "resources/ views/ components/ label.blade.php" and paste the below code

<div>
    <label class="fw-bold h6">
        {{ $slot }}
    </label>
</div>


Step 2: Now, use the label component in your view: in any blade file as given below.

<x-label>
    My Label - First Name
</x-label>


There is also another way of using slots in Laravel. Let's see how to use them and we will same example as <label>

Step 1: Open the label.blade.php component file in the following folder "resources/ views/ components/ label.blade.php" and paste the below code:

<div>
    <label class="fw-bold h5">{{ $mainTitle ?? '' }}</label>
    <label class="fw-bold h6">{{ $subTitle ?? '' }}</label>
</div>

Step 2: Now, use the label component in your view: in any blade file as given below.
Note: name attribute value in the x-slot (<x-slot name="mainTitle" is the variable created in your component i.e $mainTitle, both should be same. 

<x-label>
    <x-slot name="mainTitle">This is Main Title Data</x-slot>
    <x-slot name="subTitle">This is a sub title</x-slot>
</x-label>


That's it developer for Laravel Blade Component concepts.
If you want to learn more about the latest Laravel blade component concepts, read the official documentation: https://laravel.com/docs/10.x/blade  

Thanks for reading.