DEV Community


Posted on

Useful Laravel Blade Directives

Laravel Blade Directives are syntactic sugar functions that hide the underlying complex and ugly code. This make code more readable and clear.

Blade includes lots of built-in directives. But, this tutorial will help you with laravel blade directives that you’ll often reach out during your time in laravel.

1. Check whether the user is a guest or not using blade directive

This helps to check if the user is a guest i.e., not an authenticated user. For this purpose we use:

    // The user is not authenticated.

To make this even easier, the blade provides us with @guest a directive. This helps to write code in a much shorter way.

    // The user is not authenticated.

2. Check if the user is authenticated or not using blade directive

To check this, we can use the code given below:

    // The user is authenticated.

The above code works fine but as a programmer, we should always look for easy and shorter ways to write code. For that purpose, laravel provides blade directive which is @auth.

    // The user is authenticated.

To combine the two directives we can use else:

    // The user is not authenticated.
    // The user is authenticated.

3. Include first view if it exists else include second view

Most of the websites nowadays have multiple themes. This might require us to include a file if it exists else include another file. We can easily achieve this by using laravel:


We can write the above code in much easier and shorter way with blade.

@includeFirst(['first-view-name', 'second-view-name']);

You can continue this post on

Top comments (1)

bdelespierre profile image
Benjamin Delespierre • Edited

Also very useful

@can('edit', $post)
  <a href="{{ route('post.edit', $post) }}">Edit Post</a>

@cannot('view', $post)
   <p>You cannor view this post!</p>

@includeWhen(auth()->user()->isAdmin(), 'admin_panel')

{{-- in your layout template --}}
  <script src="jquery.js"></script>

{{-- anywhere you want --}}
  <script>$(function() { $('button').click(function() { alert("Hello!"); }); });</script>

@each('post.view', $posts, 'post', 'post.empty')

@inject('metrics', 'App\Services\MetricsService')
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.