Learn to Create a Blade Components and Slots in Laravel

1
2363
Blade Components

With Laravel 5.4 and above, you can add components and slots to your blade views using the @component and @slot directive. If you’re already familiar with using blade, the concept of components and slots is very similar to section and layouts. Using blade components and slots allows you to easily build and implement reusable HTML elements in your view.

Getting Started

We will have a master layout with an alert component that needs to be reusable. Head over to the resources/views directory and create an alert.blade.php file. Edit the file with the following code:

The {{$slot}} variable contains the content we plan on injecting into our component. Create a master.blade.php file in the resources/views directory and add the following code to it:

Using the @component directive, we inject the alert component we created earlier and append it to the master view.

Making Components Reusable

At the moment our component isn’t really reusable. Take for instance, what if I want to display a success and danger alert using the same component? Or I need my alert to have custom titles?

Let’s fix that. Initially , I need the alert’s class and title to be reusable. So we’ll define a class and title variable in the alert component we created earlier. Edit the alert.blade.php to look like this now:

Now, we have been able to define multiple slots for a class and title variable in our component. We can now reference those slots in our alert component. Edit the master.blade.php with the following code:

Now we have two alert components – a success and error component. Using @slot(‘class’) and @slot(‘title), we parsed in values to the class and title variables we defined earlier in our components allowing us to achieve reusability.

Routes
We have only a single route. Edit the web/routes.php file with the following code:

You can start your local server and navigate to the /component route in your browser to see everything in action.

Conclusion: –
In this simple tutorial, we have learnt how to build reusable HTML views using components and slots.

1 COMMENT

  1. Thanks! I was able to fully understand the use through this article – especially the example here. Much appreciated!

LEAVE A REPLY

Please enter your comment!
Please enter your name here