How To Use Laravel 7 Blade Component [New Feature in Laravel 7]

This blog post describes how to use the Laravel 7 blade component. which is come in the Laravel 7 new feature.

Laravel blade component is a new feature that comes in the Laravel 7 version. This blog post will describe how to use the Laravel Blade component and why we use it?.

Why we use Laravel blade Component?

Laravel Blade Component Make Easier to development task and also improve development speed. This is works like the Vue js component.

So what we do in the Laravel blade component?

Suppose I group of a button or an alert or something another code that we need the same code on many other pages.

Step: 1 Create a new Laravel 7 Application

Create a new Laravel application using this command.

laravel new bladeapp

Step: 2 Create an Alert Component

Create a new Component using the following command which we use many pages.

php artisan make:component Alert

After running this command you can see two new files created in 

resources\views\components\alert.blade.php

App\View\Components\Alert.php

Step: 3 Change alert.blade.php

Now add some code in resources/views/components/alert.blade.php for show success alert box.

alert.blade.php

<div >
  <h4 >{{ $message }}</h4>
</div>

Step: 4 Change welcome.blade.php

Now Change welcome.blade.php to import alert.blade.php

use Bootstrap CDN at the top of the page.

<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin=anonymous>
       
<x-alert message="Welcome To CoderMen"  />

Step: 5 Defile “message” variable in Alert.php

Alert.php

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
    
    public $message;
    
    public function __construct($message)
    {
        $this->message = $message;
    }

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

Step: 6 Now run your application 

How To Use Laravel 7 Blade Component [New Feature in Laravel 7]

Ok, now if you want to pass some more data to alert.blade.php like class name of the alert. 

So change this.

1. welcome.blade.php

Now you can change classes like success, danger, and warning. also, change the title.

@component('components.alert')
    @slot('class')
        success
    @endslot
    @slot('title')
        Success Message
    @endslot
    Hello CoderMen.
@endcomponent

And Change Also. in alert.blade.php

<div >
  <h4 >{{ $title }}</h4>
  <p>{{ $slot }}</p>
</div>

Now Result will be.

Laravel Blade Component

So here We Completed Tutorial on How To Use Laravel 7 Blade Component hope it will help you.