Laravel 8 Tutorial - Blade Components

In this video, we will learn about Blade Components in Laravel. Components provide benefits to sections and layouts, and there are two approaches to creating them: class-based components and anonymous components.

To create a class-based component, we use the make:component Artisan command. Let's create a class component. Switch to the command prompt and write the command:


php artisan make:component HeaderComponent

This command creates two files: one in the app/view/components directory, which is the component class file, and another in the resources/views/components/ folder, which is the component view template file.

Open the header.php file, which is the component class file. It has a render method that returns the header view by default. Now, add some text to the header template file:


<h1>This is a header</h1>

Save the file. To display a component, we use a Blade component tag inside Blade templates. Blade component tags start with the string x- followed by the name of the component class.

Go to the view file and open the welcome.blade.php file. Inside the file, type:


<x-header/>

Save the file and let's check. Switch to the browser and refresh the page. You can see the header component showing here.

Now, let's pass some data to the component. Go to the welcome.blade.php file and type:


<x-header name="Surfside Media"/>

Go to the header component class and inside the constructor, pass a parameter $name and create a public class variable:


public $name;

public function __consruct($name)
{
$this->name = $name;
}

Now, go to the header.blade.php file and print the $name variable value:


<h3>Hello {{$name}} </h3>

Save the file and let's check it. Switch to the browser and refresh the page. You can see the output.

You can also pass data from a controller. Let's see how to pass data from a controller. First, create a controller:


php artisan make:controller HomeController

Go to the HomeController and inside the index method, create an array variable:


public function index()
{
$fruits = array('mango','orange','apple','pineapple','banana');
return view('welcome',['fruits'=>$fruits]);
}

Go to the welcome.blade.php file and type:


<x-header name="Surfside Media" :fruits="$fruits" />

Save the file and go to the Header.php component class file. Inside the constructor, add one more parameter $fruits and create a public class variable:


public $fruits;

public function __consruct($fruits)
{
$this->fruits = $fruits;
}

Now, print the fruits array to the header component view:


@foreach($fruits as $fruit)
<p>{{$fruit}}</p>
@endforeach.

Save the file and finally modify the welcome route:


Route::get('/', [HomeController::class, 'index']);

Save all and let's check. Switch to the browser and refresh the page. You can see the fruits name here.

In this way, you can create and use Blade components in Laravel 8.