Laravel UI Development: Simplifying with Blade Components
Posted on April 8th, 2024
Blade is Laravel’s simple yet powerful template engine that allows you to write code in plain PHP language in your templates. It makes syntax writing very simple. The blade templating engine provides its structure, such as variables, conditional statements, and loops.
Blade template uses .blade.php file extension and is stored in the resources/view directory. The main advantage of using Laravel Blade is you can make your code into reusable modules that you can easily add, remove, or delete without affecting the whole application.
Understanding the Basics of Blade components
Laravel blade components are reusable pieces of code that encapsulate specific UI elements in your Laravel application. This keeps your code clean, organized, and easier to maintain. Here are examples of blade components.
- Buttons: Create a component with different styles (primary, secondary), sizes (large, small), and functionalities (submit, cancel).
- Alerts: Design a component for displaying success, error, or informational messages.
- Navigation Bars: Build a reusable component for your application’s navigation with links and dropdown menus.
Getting Started with Blade Components
1. Creating a Laravel Project
Open the command line and run the below command to create a Laravel project.
composer create-project laravel/laravel my-laravel-project
Now navigate to the project:
cd my-laravel-project
And start the development server.
php artisan serve
2. Create a Blade Component
Open the terminal and locate the project directory and run the below command to create the component.
php artisan make:component Alert
This command creates an Alert.blade.php file inside the resources/views/components directory.
Now, add the following code to your Alert.blade.php file.
<div class=”alert alert-primary” role=”alert”>
{{ $slot }}
</div>
This view uses a $slot to render the content passed to the component.
3. Use the Alert Component in the Template
Next, we can use the component in the resources/views/welcome.blade.php file. Add the following code in the welcome.blade.php file.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Laravel Blade Component Example</title>
<link href=”{{ asset(‘css/app.css’) }}” rel=”stylesheet”>
</head>
<body>
<div class=”container”>
<h1>Welcome to Blade Components!</h1>
<x-alert>This is an alert message!</x-alert>
</div>
</body>
</html>
If the casings don’t match, change the component usage in your Blade template to the exact casing of the component directory (e.g., x-Alert if the directory is Alert.blade.php)
4. Run the Application
Start the development server using the below command.
php artisan serve
Open the web browser and navigate to http://127.0.0.1:8000/. You’ll see the message below.
Simplifying UI Development with Blade Components
1. Passing Data to the Blade Component
Components can receive data using attributes passed during usage. Let’s modify the Alert component to accept a title prop.
Modify your Alert.blade.php file by following the code.
<div class=”alert alert-{{ $type }}”>
@if ($title)
<h4>{{ $title }}</h4>
@endif
{{ $slot }}
</div>
Now update template usage which is welcome.blade.php.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Laravel Blade Component Example</title>
<link href=”{{ asset(‘css/app.css’) }}” rel=”stylesheet”>
</head>
<body>
<div class=”container”>
<h1>Welcome to Blade Components!</h1>
<x-Alert title=”Success Message” type=”success”>
This is a successful operation.
</x-Alert>
</div>
</body>
</html>
Now, you can pass custom titles to your alert messages using the title prop.
You can reuse chunks of code representing UI elements like buttons, alerts, or navigation bars. By using components, you can Reduce Code Duplication, Improve Maintainability, Enhance Code Organization, and Boost Developer Experience.
Let’s create blade components for layouts and repeated elements.
2. Blade component for layout and updated elements
Suppose you create an application in which the navbar is standard for all the pages. At that time, the blade component plays a crucial role in reusing code that can be included in every application view.
1. Navigation component
Create a Navigation.blade.php(inside resources/views/components) component for your navigation bar. This file holds the code for your reusable navigation bar component.
Add the following line of code to your Navigation.blade.php file.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Navbar Example</title>
<link href=”https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css” rel=”stylesheet”>
</head>
<body>
<nav class=”navbar navbar-expand-lg navbar-light bg-light”>
<a class=”navbar-brand” href=”#”>Your App Name</a>
<button class=”navbar-toggler” type=”button” data-toggle=”collapse” data-target=”#navbarSupportedContent” aria-controls=”navbarSupportedContent” aria-expanded=”false” aria-label=”Toggle navigation”>
<span class=”navbar-toggler-icon”></span>
</button>
<div class=”collapse navbar-collapse” id=”navbarSupportedContent”>
<ul class=”navbar-nav mr-auto”>
<li class=”nav-item active”>
<a class=”nav-link” href=”#”>Home <span class=”sr-only”>(current)</span></a>
</li>
<li class=”nav-item”>
<a class=”nav-link” href=”#”>About</a>
</li>
<li class=”nav-item dropdown”>
<a class=”nav-link dropdown-toggle” href=”#” id=”navbarDropdown” role=”button” data-toggle=”dropdown” aria-haspopup=”true” aria-expanded=”false”>
Services
</a>
<div class=”dropdown-menu” aria-labelledby=”navbarDropdown”>
<a class=”dropdown-item” href=”#”>Service 1</a>
<a class=”dropdown-item” href=”#”>Service 2</a>
<div class=”dropdown-divider”></div>
<a class=”dropdown-item” href=”#”>More Services</a>
</div>
</li>
</ul>
</div>
</nav>
<script src=”https://code.jquery.com/jquery-3.5.1.slim.min.js”></script>
<script src=”https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js”></script>
<script src=”https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script>
</body>
</html>
2. Main Layout
Next, we have to create an application layout that can serve the code for most of your application views.
Create an app.blade.php file inside the resources/views/layouts folder and add the following line of code to it.
<!DOCTYPE html>
<html>
<head>
<title>@yield(‘title’)</title>
</head>
<body>
@include(‘components.Navigation’) {{– Include the Navigation component –}}
<div class=”container”>
@yield(‘content’) {{– Placeholder for content specific to each view –}}
</div>
</body>
</html>
3. Application Views
In the welcome.blade.php file(already created in the resources/views folder), we need to extend the main layout (app.blade.php) and define their specific content within designated sections.
Add the following line of code in the welcome.blade.php file inside the body tag.
@extends(‘layouts.app’)
@section(‘title’)
Welcome Page
@endsection
@section(‘content’)
<h1>Welcome to Your Laravel Application!</h1>
<p>This is the content of your welcome page.</p>
@endsection
By starting the development server, you’ll see a screen like the one below.
Best Practices and Tips for Blade Components
Let’s check the best practices and tips to ensure their optimal use in the Laravel application.
Naming convention and organization
Component Directory Structure: Consider organizing your components based on functionality or UI elements, for example, buttons, forms, and navigation.
Prefixing: You can use a prefix like components within your directory structure to distinguish component files further.
Here is the example structure of files and folders.
Testing Blade Components
Here are some approaches to test blade components.
- Manual Testing: This includes creating a test view and rendering the component with different data.
- Unit Tests: Use a testing framework like PHPUnit to create unit tests that focus on the component’s logic.
- Feature Tests: Integrate component testing within feature tests that simulate user interactions and test the overall application flow.
Here are example unit tests using PHPUnit
<?php
namespace Tests\Feature\Components;
use App\Components\Alert;
use Illuminate\Support\Facades\View;
use Tests\TestCase;
class AlertTest extends TestCase
{
public function testAlertRendersSuccessMessage()
{
$type = ‘success’;
$message = ‘This is a successful operation!’;
$view = view(‘components.alert’, compact(‘type’, ‘message’));
$this->assertEquals(
‘<div class=”alert alert-success”>This is a successful operation!</div>’,
$view->render()
);
}
}
Conclusion: Mastering Laravel Blade empowers developers to create dynamic and efficient web applications with ease. By leveraging Blade’s intuitive templating syntax and powerful features, such as inheritance, includes, and control structures, developers can streamline their workflow and deliver high-quality user experiences.
With Blade, developers can separate presentation logic from application logic, resulting in clean and maintainable codebases. Additionally, Blade’s integration with Laravel’s ecosystem further enhances its capabilities, enabling seamless interaction with routes, controllers, and models.
Overall, Laravel Blade is a versatile tool that plays a crucial role in Laravel development, offering developers a flexible and efficient way to build sophisticated web applications.
Very good
Hi,
Thank you, have a great day.