10 Useful Blade Directives in Laravel

10 Useful Blade Directives in Laravel

ยท

4 min read

Blade is a very powerful template engine and provides plenty of directives to save your working time. In this article, I'm going to cover some of them.

Table of contents

  1. @forelse
  2. @include
  3. @auth and @guest
  4. @isset and @empty
  5. @production
  6. @csrf
  7. @method
  8. @class
  9. @extends, @yield and @section
  10. @can

1. @forelse

How many times have you encountered this situation you need to check if the variable is not empty like the code below.

@if(count($articles) > 0)

   @foreach($articles as $article)
       <h4>Article: {{$article->name}}</h4>
   @endforeach

@else
<span>No articles found</span>

@endif

What if I told you can do the same with forelse directive

@forelse ($articles as $article)
    <h4>Article: {{$article->name}}</h4>
@empty
    <span>No articles found</span>
@endforelse

Pretty cool right. Less code Same result

2. @include

Very helpful directive when we work with layouts because we can divide our layout into different parts and include each subview in the main view. You can use this directive like this

<div>
     @include('partials.header')
</div>

Also, you can pass variables if you wish.

<div>
     @include('partials.header', ['title' => $title])
</div>

3. @auth and @guest

Imagine this scenario we want to display a button only when the user is authenticated, you can do something like this.

@if(auth()->user())
    <button class="btn btn-success"> My books </button>
@endif

works fine but a pretty neat solution is to use @auth directive:

@auth
     <button class="btn btn-success"> My books </button>
@endauth

Of course, @guest works when a user is not authenticated. For example.

@guest
<a href="{{route('login')}}" class="btn btn-primary"> Login </a>
@endguest

4. @isset and @empty

Of course, these directives are the same that isset() and empty() PHP functions but in form of blade directives, @isset checks if the variable is defined and is not null, and @empty checks if the variable is not empty.

@isset($companies)
    //Put your code here
@endisset

@empty($companies)
    //Put your code here
@endempty

5. @production

This directive is very useful when we need to check if our application is running in production and execute the code you require in that environment.

@production
 //The code you need to execute in production
@endproduction

6. @csrf

When we work with HTML forms we should include a CRSF token in order to prevent this kind of attacks, in our form we can define an input hidden like this

 <input type="hidden" name="_token" value="{{ csrf_token() }}" />

But @csrf directive will generate the same hidden token with less code. For example.

<form method="POST" action="/products">
    @csrf

</form>

Both methods are equivalent. You can decide which one wants to use.

7. @method

HTML form is not supporting PUT, PATCH, DELETE requests only GET and POST, so how we can resolve this problem, in this case, we need to put @method directive in ours forms. For example:

<form action="{{route('categories.update', $category->id)}}" method="POST">
    @method('PUT')

</form>

8. @class

It's very useful if want to use a css class conditionally. For example, let's say if the $hasError variable is true, you want to put a red background in the input field and also a red border.

<input @class([
    'p-4',
    'bg-red' => $hasError,
    'border-red-500' => $hasError,
])>

if this case, the output will be

<input class="p-4 border-red-500 bg-red" type="text">

Otherwise, if the variable $hasError = false

<input class="p-4" type="text">

9. @extends, @yield and @section

In this example, let's say we have our main layout in resources/layouts/app.blade.php inside that file we can define a @yield like this

<body>
    <main class="app-content" id="app">
        @yield('content')
    </main>
</body>

Now, suppose we have a view in resources/layouts/products.blade.php inside that file we can use @extends and @section:

@extends('layouts.app')
@section('content')
@endsection

@extends means we are extending the main layout in the child view and we can access everything from the app.blade.php like HEAD, BODY tags. @section means everything we put here automatically goes to @yield in the app.blade.php

10. @can

The security in our application is very important and many projects require roles and permissions, the @can directive allows to check if the user has the permission or not to access certain data. Let's see this example: Only the role manager can create a new warehouse. Let's do this in code:

<div class="tile-title">Warehouses
      <div class="float-right">
              @can ('warehouse_create')
               <a href="{{route('warehouse.create')}}" class="btn btn-primary">
                    New warehouse
               </a>
               @endcan
      </div>
</div>

In this case, only the person to permission to warehouse_create could see the button.

If I forgot any directives let me know in the comment section.

Happy coding โ˜•. Thanks for reading ๐Ÿ™.

ย