Laravel 7 Blade Components

Blade is a king of templating engine in laravel that permits you to use plan php in your view. Developers were introduced with new class based blade syntax for creating components in laravel 7. If you're conversant in VueJs components you'll find the thought is same but in PHP way


Laravel 7 Blade Components

By creating a blade component you are following DRY ( don't repeat yourself) principle . It means you'll reuse it in your project. So lets begin :

So lets begin :
First create a component by this command :



 php artisan make:component Alert


This command will generate two files
app\View\Components\Alert.php

this file handle variables and functions of the blade component.

resources\views\components\alert.blade.php

Now you can call this component in your project by "<x-alert>" , so you can see "x" is used to access component ,
now we would like to pass a variable name "title" within the component



<x-alert title="This is title"> </x-alert>


now open "app\View\Components\Alert.php" and add title variable in the class




 <?php

 namespace App\View\Components;
 use Illuminate\View\Component;

 class Alert extends Component
 {
    /**
     * The alert title.
     *
     * @var string
     */
    public $title;

    /**
     * Create the component instance.
     *
     * @param  string  $title
     * @return void
     */
    public function __construct($type)
    {
        $this->title= $title;
    }

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


Now $title property is accessible in our "alert" blade element. You be able to outline additional variables here and might access it within the blade element such as you can pass message or style of the alert.


more examples for the alert messages


Here we've passed 2 variables, "type" is comparable like title we tend to passed in higher than example and second is "message" however within the message variable we tend to area unit passing a PHP variable value.

now update your alert.blade.php with

 
<!-- /resources/views/components/alert.blade.php -->
 <div class="alert alert-{{ $type }}">
    {{ $message }}
 </div>


Real life example:

 
<!-- /resources/views/components/alert.blade.php -->
 <div {{ $attributes->merge(['class' => 'p-6 rounded-lg shadow-lg']) }}>
   <div class="text-xl text-orange-500">{{ $title }}</div>
    <div class="mt-4">
        {{ $slot }}
    </div>
 </div>


call it in your project:


 
<x-panel title="Update Your Info!" class="max-w-2xl">
    <h1>I AM IN THE SLOT</h1>
 </x-panel>


Thank you,🤗

Latest
Next Post

Hello, I am Ashish Yadav. Youtuber | Blogger | Programmer | Digital Marketer. Working on 3 Youtube Channel: 1. Expo Ashish 2. Expo Facts 3. Best Code Creator

Related Posts

Do Subscribe My Youtube Channel