DEV Community

loading...
Cover image for Laravel 7 Blade Components

Laravel 7 Blade Components

ajayyadav profile image Ajay Yadav ・2 min read

Blade is a templating engine in laravel that allows you to use plan php in your view.In laravel 7 developers were introduced with new class based blade syntax for creating components. If you are familiar with VueJs components you will find the idea is same but in PHP way.

By creating a blade component you are following DRY ( don't repeat yourself) principle . it means you can reuse it in your project.

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

 php artisan make:component Alert
Enter fullscreen mode Exit fullscreen mode

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 want to pass a variable name "title" in the component

<x-alert title="This is title"> </x-alert>
Enter fullscreen mode Exit fullscreen mode

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');
    }
}


Enter fullscreen mode Exit fullscreen mode

Now $title property is accessible in our "alert" blade component. you can define more variables here and can access it in the blade component like you can pass message or type of the alert.

more examples for the alert messages


here we have passed two variables, "type" is similar like title we passed in above example and second is message but in the message variable we are 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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

call it in your project

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

Thank you,🤗

Discussion (0)

pic
Editor guide