Skip to main content

Command Palette

Search for a command to run...

Laravel blade

Ever heard of making cool websites? Well, Laravel Blade is like the superhero helping developers do just that!

Updated
8 min read
Laravel blade
A

Behold, the coding maestro! 🎩 Armed with PHP, Laravel, Linux, HTML, JavaScript, Jquery & Vue, I conquer both frontend and backend realms. 🚀 Pressure? No match for me. I deliver excellence and exceed expectations with flair. 🌟 Stay ahead, stay cool, and let's conquer the coding universe together! 💻

Blade is the templating engine that comes with Laravel to give us the efficient and clean rendering of views which is essential for creating dynamic and visually appealing web applications. Laravel Blade provides a simple yet robust syntax to work with views and helps developers create layouts, partials, and components with ease. It's friendly for people just starting out in web development and also has some secret tricks that more experienced developers can use to make websites work even better. Blade basically makes web building more like fun arts and crafts than hard computer stuff. Blade template files use the .blade.php file extension and are typically stored in the resources/views directory of Laravel.

Why Laravel Blade?

  1. Clean and Expressive Syntax

    Blade's syntax is like a breath of fresh air in the web development world. It's a mix of regular HTML and simple codes that make it super-readable and easy to understand. Unlike raw PHP, Blade keeps things tidy, making it a delight for developers to work with.

  2. Template Inheritance for Consistency

    One big reason we love Blade is its template inheritance feature. This means you can create a layout for your website once and use it everywhere without rewriting the same code. It's like having a master plan for your website's design that you can reuse effortlessly.

  3. Encourages Best Practices

    Blade encourages separating different parts of your code, like keeping logic in one place and design in another. This separation of concerns helps in better organization and makes your code easier to understand and maintain.

  4. Directives and Control Structures

    Laravel Blade offers powerful directives and control structures (such as loops, conditional statements, and includes) to manipulate data and control the flow of the application logic directly within the views.

  5. Performance and Optimization

    Blade doesn't just make things pretty, it's also efficient. Laravel allows caching views created with Blade, which means your website can load faster by saving pre-rendered views, especially useful for frequently visited pages.

  6. Community and Support

    Laravel, with Blade as its shining star, has a vibrant community. This means plenty of resources, tutorials, and support available online. If you ever get stuck or want to learn more, there's always a helping hand or a tutorial just a click away.

Basics of Laravel Blade

  1. Introduction to Blade Syntax

    1. Echo Variables {{$name}} shows the content of a variable, like displaying a person's name stored in $name, and it's automatically sent through PHP's htmlspecialchars function to prevent XSS (Cross-site scripting) attacks.

      You are not limited to just printing the values stored in the variable you can print the result of functions as well as you can you can put any PHP code you wish inside of a Blade echo statement

       <!-- Displaying Variables -->
       {{ $name }}
      
       <!-- Displaying resut of a funtion -->
       The current UNIX timestamp is {{ time() }}.
      
    2. IF conditions in Blade: It checks if someone is logged in ($isLoggedIn). If true, it says a welcome message with the name; otherwise, it asks to log in.

       @if($isLoggedIn)
           <p>Welcome, {{ $username }}!</p>
       @endif
      
       <!-- Using @if/@else -->
      
       @if($isAdmin)
           <p>Welcome, Admin!</p>
       @else
           <p>Welcome, User!</p>
       @endif
      
       <!-- Using @if/@elseif/@else -->
      
       @if($userRole === 'admin')
           <p>Welcome, Admin!</p>
       @elseif($userRole === 'moderator')
           <p>Welcome, Moderator!</p>
       @else
           <p>Welcome, User!</p>
       @endif
      
    3. Loops in Blade:

      Laravel Blade provides several directives for looping through arrays or collections and offers loop-related variables to access information about the current iteration. Let's explore each loop directive and its associated loop variables.

      1. @foreach Loop

        • Initiates a loop through the $items array or collection. $items represent the data source being iterated, and $item is the loop variable that holds each item during iterations.

        • <p>{{ $item }}</p>: Within the loop, {{ $item }} displays each item in the $items array within <p> tags.

            @foreach($items as $item)
                <p>{{ $item }}</p>
            @endforeach
          
      2. @forelse Loop:

        The @forelse directive in Laravel Blade is specifically designed to handle looping through data while also managing empty states more elegantly compared to traditional loops.

        @empty: This section is executed if the $user array is empty. It shows a message, like "No users"

         @forelse ($users as $user)
             <li>{{ $user->name }}</li>
         @empty
             <p>No users</p>
         @endforelse
        
      3. @for Loop:

        • @for($i = 0; $i < count($numbers); $i++): Sets up a traditional for loop. Here, $i serves as the loop counter starting from 0, iterating until the condition is met ($i < count($numbers)).

        • <p>{{ $numbers[$i] }}</p>: Displays each element of the $numbers array using the loop counter $i to access individual elements.

             @for($i = 0; $i < count($numbers); $i++)
                 <p>{{ $numbers[$i] }}</p>
             @endfor
          
      4. @while Loop

         @php
             $counter = 0;
         @endphp
        
         @while($counter < 5)
             <p>{{ $counter }}</p>
             @php
                 $counter++;
             @endphp
         @endwhile
        
      5. Loop Variables in Blade:

        1. $loop->index The index of the current loop iteration (starts at 0).

        2. $loop->iteration The current loop iteration (starts at 1).

        3. $loop->remaining The iterations remaining in the loop.

        4. $loop->count The total number of items in the array being iterated.

        5. $loop->first Whether this is the first iteration through the loop.

        6. $loop->last Whether this is the last iteration through the loop.

        7. $loop->even Whether this is an even iteration through the loop.

        8. $loop->odd Whether this is an odd iteration through the loop.

        9. $loop->depth The nesting level of the current loop.

        10. $loop->parent When in a nested loop, the parent's loop variable.

            $countries = ['USA', 'Canada', 'UK', 'Australia'];

            @foreach($countries as $country)
                <p>
                    Index: {{ $loop->index }} |
                    Iteration: {{ $loop->iteration }} |
                    First: {{ $loop->first ? 'Yes' : 'No' }} |
                    Last: {{ $loop->last ? 'Yes' : 'No' }} |
                    Count: {{ $loop->count }} |
                    Total Items: {{ $loop->total }} |
                    Odd/Even: {{ $loop->odd ? 'Odd' : 'Even' }} |
                    {{ $country }}
                </p>
            @endforeach
  1. @switch @case and @default

    The @switch, @case, and @default directives in Laravel Blade provide a structured way to handle complex conditional logic. They function similarly to the switch-case-default construct in PHP.

     @switch($role)
         @case('admin')
             <p>Welcome, Admin!</p>
             @break
    
         @case('user')
             <p>Welcome, User!</p>
             @break
    
         @default
             <p>Unknown Role</p>
     @endswitch
    

Laravel Blade Directives

Blade directives are special syntax or instructions used in Laravel Blade templates to streamline and enhance the readability and functionality of your views. Here's an overview of some commonly used Blade directives

  1. @include

    1. The @include directive in Laravel Blade is used to include and render other Blade views or partials within a Blade template. It enables the reusability of code by allowing you to insert the contents of another Blade file into the current file.

      This includes the content of the partials/header.blade.php file in the current Blade template at the location where the @include directive is placed.

       @include('partials.header')
      
    2. With Variables

      In this case, the partials/product.blade.php file is included, and it's passed a variable $product to use within that included file.

       $product = App\Models\Product::all();
      
       @include('partials.product', ['product' => $product])
      
       <!-- Second Exampe -->
      
       @include('partials.product', compact('product'))
      
  2. @includeWhen

    The @includeWhen directive in Laravel Blade is a conditional way to include a Blade view or partial based on a given condition. It's similar to the @include directive but includes the specified view only when the condition provided evaluates to true.

    Difference between @include and @includeWhen:

    @include It unconditionally includes the specified Blade view or partial in the current template regardless of any condition.

    It's used for unconditional inclusion.

    @includeWhen: It includes the specified view based on a condition. If the condition is true, the view is included; otherwise, it's skipped. It's suitable for conditional inclusion.

     @includeWhen($condition, 'partials.header')
      <!-- With Variable -->
     @includeWhen($user->isAdmin(), 'partials.admin-menu', ['user' => $user])
    
  3. @auth and @guest

    The @auth and @guest directives in Laravel Blade provide convenient ways to conditionally display content based on whether a user is authenticated (@auth) or is a guest (not authenticated, @guest). These directives simplify the rendering of specific content based on the user's authentication status.

     @auth
         <!-- Display content if user is authenticated -->
     @endauth
    
     @guest
         <!-- Display content if user is a guest (not authenticated) -->
     @endguest
    
  4. @isset and @empty

     @isset($variable)
         <!-- Display content if $variable is set and not null -->
     @endisset
    
     @empty($items)
         <!-- Display content if $items is empty -->
     @endempty
    
  5. @verbatim
    The @verbatim directive in Laravel Blade is used to render content as raw, plain text, ignoring Blade's default templating behavior. This directive allows you to display code snippets, text blocks, or any content without being processed by Blade's syntax parser.

    Avoid excessive use of @verbatim as it bypasses Blade's powerful templating capabilities. It's typically used sparingly in specific scenarios where you need to preserve the original content without modification by Blade.

    In this case, the content inside @verbatim will be displayed exactly as written, without Blade interpreting the {{ }} or @if conditions. The entire block will be rendered as plain text.

     @verbatim
         <p>{{ $name }}</p>
         @if($status == 'active')
             <span>Status: Active</span>
         @else
             <span>Status: Inactive</span>
         @endif
     @endverbatim
    
  6. @csrf

    @csrf in Laravel Blade is a directive used for security purposes, specifically to prevent Cross-Site Request Forgery (CSRF) attacks. CSRF attacks occur when a malicious website tricks a user's browser into performing actions on another site without the user's knowledge, using their authenticated session.

    By using @csrf in your forms, Laravel ensures that your application is better protected against CSRF attacks, safeguarding the actions performed by your users.

     <form method="POST" action="/submit">
         @csrf
         <!-- Other form fields -->
         <button type="submit">Submit</button>
     </form>
    

Conclusion

Laravel Blade is a super easy way to make awesome websites and web applications. It's like using magic blocks to build your webpage. With simple commands, you can create cool designs, show different things to different people, and keep your site safe. Plus, it helps your webpage load faster, and there are lots of online friends to help you learn more. Start using Blade and make something amazing!

More from this blog

A

Abhishek Jha

15 posts

As a Full Stack Developer with four years of extensive expertise in the field of PHP, Laravel, MySQL, Linux, HTML, JavaScript, Jquery & Vue