Things to know in Laravel : chapter three


Today we’re going to talk about Laravel blade template and how to write clean code in the template. Blade is the simple, yet powerful templating engine provided with Laravel. We love blade right ? 🙂 Laravel Blade provides us many directives and other things for tidying up our blade template. Directives likes :

  1. @include
  2. @foreach
  3. @if
  4. @component slot and many others

Getting Started

Blade has special features like template inheritance and directives and unlike many other php template engine , Blade does not restrict you from using plain PHP code in your views. The traditional blade template demonstration would be :

And extending the master template :

This is how we do it. For making our views clean and readable, laravel provides many helpful directives and all. An example , let’s use foreach loop in our view :

Nice and easy right . And if we want to see if the collection is empty and return something instead of showing the list we could always make right use of @forelse.

This is equivalent to @if ($rows) . The above demonstration seems more readable.

Let’s talk about our partials and all. In a traditional html template, we have header, footer, sidebar, navbar and all . Instead of keeping all those details in our master template. We could always make use of partials for all and include them.

This way , we can have a nice, clean master template.

Let’s talk about partials , in our above foreach code demonstration we used li element . Let’s make it more cleaner. Now how do we do it ? We can make another include for that tr.

This example seems bad but for the sake of simplicty, this seems alright. 🙂 And lastly we can make it more cleaner using @each directive.

We could always use directive like @isset instead of

Writing PHP code in blade :


#Laravel 5.4^, Last one, laravel component and slot directives . If you are familiar with Vue.js components and slot, this is nothing new to you. Using component and slot, we can make reusable components or partials. You would say we can may use includes too right ? Not after seeing all of these feature laravel component and slot provides together.

In all of our code demonstration we used table so let’s make a table component.

Component is same as when we make partials and include them. $slot is where everything in between our @component directive will show up. You see we have created $header , which is named slot.

In this demonstration, we created component and make use of slot and also created our own named slot header. There are other many things that we can do to make our views more cleaner and more readable.

Happy coding 🙂

Sharing is caring!

Related Post