Understanding Laravel Blade and How To Use It

Introduction
Laravel Blade is a powerful templating engine that lets you use PHP features in your HTML code. It also helps you organize your code into reusable modules, encapsulate functions, and improve performance. In this article, you will learn how to use Laravel Blade to create dynamic web pages with layouts, data, control structures, and custom extensions.
What is Laravel Blade?
Laravel Blade is the default templating engine for the Laravel framework. It allows you to write HTML code with embedded PHP expressions, variables, loops, conditional statements, and other features. Blade files have the .blade.php extension and are stored in the resources/views directory of your Laravel project.
Blade views are compiled into plain PHP code and cached until modified, making them fast and efficient. Blade also provides several directives and helpers that make your code more readable and expressive.
How to Use Laravel Blade?
To use Laravel Blade, you must have a Laravel project set up and running. You can create a new Laravel project using Composer:
composer create-project laravel/laravel my-app
Then, you can serve your application using the php artisan serve command and access it in your browser.
To create a Blade view, you need to create a file with the .blade.php extension in the resources/views directory. For example, you can create a file called welcome.blade.php with the following content:
<!DOCTYPE html>
<html>
<head>
<title>Laravel Blade</title>
</head>
<body>
<h1>Welcome to Laravel Blade</h1>
<p>This is a simple Blade view.</p>
</body>
</html>To render a Blade view, you need to use the view helper function in your routes or controllers. For example, you can create a route in the routes/web.php file that returns the welcome view:
Route::get('/', function () {
return view('welcome');
});Now, if you visit the / URL, you will see the welcome view in your browser.
How to Use Layouts, Data, and Control Structures in Laravel Blade?
One of the main benefits of Laravel Blade is that it allows you to create layouts, pass data, and use control structures in your views.
Layouts
Layouts are Blade views that contain common elements of your web pages, such as headers, footers, navigation bars, etc. You can create a layout file in the resources/views directory and use the @extends directive to specify which layout a child view should use. For example, you can create a file called layout.blade.php with the following content:
<!DOCTYPE html>
<html>
<head>
<title>Laravel Blade - @yield('title')</title>
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>The @yield directive defines a section that will be filled by the child view. You can use the @section directive in the child view to define the content of the section. For example, you can create a file called about.blade.php with the following content:
@extends('layout')
@section('title', 'About')
@section('content')
<h1>About Laravel Blade</h1>
<p>Laravel Blade is a powerful templating engine.</p>
@endsectionThe @extends directive indicates that the about view extends the layout view. The @section directive defines the content of the title and content sections. The @endsection directive closes the section. You can also use the @stop or @show directives instead of @endsection.
To render the about view, you need to use the view helper function in your routes or controllers. For example, you can create a route in the routes/web.php file that returns the about view:
Route::get('/about', function () {
return view('about');
});Now, if you visit the /about URL, you will see the about view with the layout view applied.
Data
Data are variables or arrays that you can pass from your routes or controllers to your views. You can use the with method or the second argument of the view helper function to pass data to your views. For example, you can pass a name variable to the welcome view:
Route::get('/', function () {
return view('welcome')->with('name', 'John');
});Or:
Route::get('/', function () {
return view('welcome', ['name' => 'John']);
});You can access the data in your views using the {{ }} syntax, which will echo the data after escaping any HTML characters. For example, you can modify the welcome.blade.php file to display the name variable:
<!DOCTYPE html>
<html>
<head>
<title>Laravel Blade</title>
</head>
<body>
<h1>Welcome to Laravel Blade, {{ $name }}</h1>
<p>This is a simple Blade view.</p>
</body>
</html>Now, if you visit the / URL, you will see the welcome view with the name variable displayed.
You can also use the {!! !!} syntax to display the data without escaping any HTML characters. This is useful if you want to display HTML code from your data. However, you should be careful with this syntax, as it may expose your application to cross-site scripting (XSS) attacks. For example, you can pass an html variable to the welcome view:
Route::get('/', function () {
return view('welcome', ['html' => '<strong>Hello</strong>']);
});And display it using the {!! !!} syntax:
<!DOCTYPE html>
<html>
<head>
<title>Laravel Blade</title>
</head>
<body>
<h1>Welcome to Laravel Blade, {!! $html !!}</h1>
<p>This is a simple Blade view.</p>
</body>
</html>Now, if you visit the / URL, you will see the welcome view with the html variable displayed as HTML code.
Control Structures
Control structures are PHP statements that control the flow of your code, such as if, else, elseif, switch, case, for, foreach, while, etc. You can use these statements in your views using the @ prefix. For example, you can use the @if directive to conditionally display some content in your views:
@if($name == 'John')
<p>You are John.</p>
@elseif($name == 'Jane')
<p>You are Jane.</p>
@else
<p>You are not John or Jane.</p>
@endifYou can also use the @unless directive to display some content unless a condition is true:
@unless($name == 'John')
<p>You are not John.</p>
@endunlessYou can use the @switch directive to switch between multiple cases:
@switch($name)
@case('John')
<p>You are John.</p>
@break
@case('Jane')
<p>You are Jane.</p>
@break
@default
<p>You are not John or Jane.</p>
@endswitchYou can use the @for directive to loop through a range of numbers:
@for($i = 0; $i < 10; $i++)
<p>The current value is {{ $i }}</p>
@endforYou can use the @foreach directive to loop through an array:
@foreach($users as $user)
<p>The current user is {{ $user->name }}</p>
@endforeachYou can use the @while directive to loop while a condition is true:
@php
$i = 0;
@endphp
@while($i < 10)
<p>The current value is {{ $i }}</p>
@php
$i++;
@endphp
@endwhileYou can also use the @break and @continue directives to break or continue a loop:
@foreach($users as $user)
@if($user->name == 'John')
@break
@endif
<p>The current user is {{ $user->name }}</p>
@endforeach@foreach($users as $user)
@if($user->name == 'John')
@continue
@endif
<p>The current user is {{ $user->name }}</p>
@endforeachHow to Create Custom Extensions in Laravel Blade?
Laravel Blade also allows you to create your own custom directives and components to extend its functionality.
Custom Directives
Custom directives are custom keywords that you can define and use in your views. You can create custom directives using the Blade::directive method in the app/Providers/AppServiceProvider.php file.
Create a Custom Directive:
- Open your
AppServiceProvider.phpfile (located in theapp/Providersdirectory). - In the
bootmethod, use theBlade::directivemethod to define your custom directive. For example, you can create a custom directive called@hellothat displays a greeting message:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Blade::directive('hello', function ($expression) {
return "<?php echo 'Hello, ' . $expression; ?>";
});
}
}- Replace
'hello'with your desired directive name and provide the logic inside the closure.
Use Your Custom Directive:
- In your Blade views, you can now use the
@hellodirective. For instance:
<p>@hello('world')</p>This will render as:
Hello, world
Custom Components
Blade components allow you to create reusable UI elements. You can define your own custom components and use them across your application. Here’s how to get started:
Create a Custom Component:
- Create a new Blade component using the
php artisan make:componentcommand. For example:
php artisan make:component MyButton- This will generate a
MyButton.phpfile in theView/Componentsdirectory.
Define the Component Logic:
- Inside
MyButton.php, define the component’s logic. You can set properties, handle actions, and render the HTML. - Example:
public function render() { return view('components.my-button'); }Create the Blade View for the Component:
- Create a Blade view file named
my-button.blade.phpin theresources/views/componentsdirectory. - Customize the HTML structure for your button component.
Use Your Custom Component:
- In any Blade view, you can include your custom component using the
<x>syntax:
<x-my-button label="Click me"></x-my-button>- The
labelattribute will be passed to your component.
Stay tuned!!! I will be back with some more cool Laravel tutorials in the next article. I hope you liked the article. Don’t forget to follow me 😇 and give some claps 👏. And if you have any questions feel free to comment. Thank you.
Thanks a lot for reading till the end. Follow or contact me via: Email: [email protected] LinkedIn: https://www.linkedin.com/in/reuben-shumba-a72aaa157/ BuyMeCoffee: https://www.buymeacoffee.com/reubenshumba REUBEN SHUMBA




