We can include a specific portion of HTML using @include in Laravel. But did you know that we can do that same job using Laravel components? In this lecture, I will show you a complete guide on Laravel component tutorial, how to create components in Laravel, how to load components in Laravel, etc.

Laravel provides an artisan command to create a blade component in laravel using make:component command. There are two approaches to writing components in Laravel like class based components and anonymous components.

laravel-9-components-tutorial

Creating Laravel Component

If you want to create a blade component in laravel, then you have to run make:component command. So run this below command to create an example component like:

php artisan make:component Alert

 

Now, this command will generate two files, one is component class and the other is component views. 

App\View\Components\Alert.php

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

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

 

And the views path is:

resources/views/components/alert.blade.php

<div>
    <!-- The best way to take care of the future is to take care of the present moment. - Thich Nhat Hanh -->
</div>

 

How to Include Laravel Component in Blade

Just update this alert blade file with your HTML like:

resources/views/components/alert.blade.php

<div>
    @if ($errors->any())
        @foreach ($errors->all() as $error)
            <div>{{$error}}</div>
        @endforeach
    @endif
</div>

 

And include this in any blade file with the following style:

resources/views/welcome.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Laravel 9.x Blade Components Tutorial | Laravelia</div>
                <div class="card-body">
                    <x-alert/>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 

Read also: How To Render Specific Fragment Of Blade In Laravel 9?

 

Conclusion

I have tried to discuss the clear concept of laravel blade component example. Now we know laravel components example. Hope this laravel components tutorial will help you.