Md Mominul Islam | Software and Data Enginnering | SQL Server, .NET, Power BI, Azure Blog

while(!(succeed=try()));

LinkedIn Portfolio Banner

Latest

Home Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Thursday, August 28, 2025

Laravel Core Complete Course: Module 3 - Mastering Blade Templating Engine for Dynamic Web Development

 


Table of Contents

  1. Introduction to Blade Templates

    • What is Blade?

    • Why Use Blade?

    • Setting Up Blade in Laravel

    • Pros and Cons of Blade

    • Alternatives to Blade

    • Best Practices and Standards

    • Example: Creating a Welcome Page

  2. Displaying Data & Blade Syntax

    • Blade’s Double Curly Brace Syntax

    • Escaping Data for Security

    • Using Raw Output with Triple Curly Braces

    • Blade Directives for Dynamic Data

    • Pros and Cons

    • Alternatives

    • Best Practices

    • Example: Building a User Profile Page

  3. Blade Control Structures (@if, @foreach)

    • Conditional Rendering with @if, @elseif, @else

    • Looping with @foreach, @forelse

    • Other Control Structures (@while, @unless)

    • Pros and Cons

    • Alternatives

    • Best Practices

    • Example: Displaying a Product Listing

  4. Layouts & Sections

    • Template Inheritance with @extends

    • Defining and Yielding Sections

    • Using @parent for Extending Content

    • Pros and Cons

    • Alternatives

    • Best Practices

    • Example: Creating a Blog Layout

  5. Components & Slots

    • Creating Reusable Components

    • Using Slots for Flexible Content

    • Component Attributes and Props

    • Pros and Cons

    • Alternatives

    • Best Practices

    • Example: Building a Reusable Card Component

  6. Conditional Rendering & Loops

    • Advanced Conditional Rendering Techniques

    • Nested Loops and Conditional Logic

    • Optimizing Performance in Loops

    • Pros and Cons

    • Alternatives

    • Best Practices

    • Example: E-commerce Product Filtering System

  7. Conclusion

    • Recap of Blade’s Power

    • Next Steps in Your Laravel Journey

    • Resources for Further Learning


1. Introduction to Blade Templates

What is Blade?

Blade is Laravel’s simple yet powerful templating engine, designed to create dynamic and reusable views with minimal overhead. Unlike traditional PHP templating, Blade uses a clean, intuitive syntax that integrates seamlessly with HTML, allowing developers to write concise and readable code. Blade templates are stored in the resources/views directory with a .blade.php extension and are compiled into plain PHP for optimal performance.

Blade’s key features include:

  • Template Inheritance: Define a master layout and extend it across multiple views.

  • Control Structures: Use directives like @if, @foreach, and @while for dynamic rendering.

  • Components and Slots: Create reusable UI elements for modular code.

  • Zero Overhead: Blade templates are cached as PHP, ensuring fast rendering.

Why Use Blade?

Blade simplifies front-end development in Laravel by separating presentation logic from business logic. It supports rapid development, promotes code reusability, and enhances maintainability. For example, a blog application can use a single Blade layout for consistent headers and footers across all pages, reducing repetitive code.

Setting Up Blade in Laravel

To start using Blade, ensure you have a Laravel project set up. If not, install Laravel via Composer:

composer create-project --prefer-dist laravel/laravel myproject

Blade templates are stored in resources/views. The default welcome.blade.php file is a good starting point. To create a new Blade template, add a file like home.blade.php in this directory.

Pros and Cons of Blade

Pros:

  • Elegant Syntax: Blade’s directives (e.g., @if, @foreach) are cleaner than raw PHP.

  • Performance: Compiles to cached PHP, minimizing runtime overhead.

  • Template Inheritance: Simplifies layout management across pages.

  • Security: Automatically escapes output to prevent XSS attacks.

  • Reusable Components: Supports modular UI development.

Cons:

  • Learning Curve: Beginners may find Blade’s directives unfamiliar compared to plain PHP.

  • Limited Logic: Complex logic in templates can make views harder to maintain.

  • Framework Dependency: Blade is tightly coupled with Laravel, limiting its use outside the framework.

Alternatives to Blade

  1. Plain PHP Templates: Simple but lack Blade’s elegant syntax and features.

  2. Twig (Symfony): A powerful templating engine with similar features but more complex syntax.

  3. Vue.js/React: Front-end frameworks for dynamic UIs, though they require JavaScript knowledge and client-side rendering.

  4. Laravel Livewire: Extends Blade with reactive components, ideal for dynamic interfaces without heavy JavaScript.

Best Practices and Standards

  • Keep Logic Minimal: Avoid complex PHP logic in Blade templates; use controllers or helpers instead.

  • Follow PSR-2/PSR-4: Adhere to Laravel’s coding standards for consistency.

  • Use Descriptive Filenames: Name templates clearly (e.g., layouts/app.blade.php).

  • Leverage Caching: Ensure Blade’s caching is enabled in production for performance.

  • Secure User Input: Use {{ }} for automatic escaping to prevent XSS attacks.

Example: Creating a Welcome Page

Let’s create a simple welcome page for a portfolio website using Blade.

Step 1: Create a RouteIn routes/web.php:

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome', ['name' => 'John Doe']);
});

Step 2: Create a Blade TemplateIn resources/views/welcome.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to My Portfolio</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <div class="container mx-auto p-4">
        <h1 class="text-3xl font-bold">Welcome, {{ $name }}!</h1>
        <p class="mt-4">This is my portfolio website built with Laravel and Blade.</p>
    </div>
</body>
</html>

Step 3: Run the Development Server

php artisan serve

Visit http://127.0.0.1:8000 to see the welcome page with “Welcome, John Doe!” displayed dynamically.

Explanation:

  • The {{ $name }} syntax displays the name variable passed from the route.

  • Tailwind CSS is used for styling, showcasing Blade’s compatibility with modern CSS frameworks.

  • The template is simple, reusable, and easy to extend.


2. Displaying Data & Blade Syntax

Blade’s Double Curly Brace Syntax

Blade uses {{ }} to display variables in templates. This syntax automatically escapes output to prevent XSS attacks, ensuring security by default. For example:

<p>Hello, {{ $user->name }}!</p>

This displays the user’s name, escaped to prevent malicious code injection.

Escaping Data for Security

Blade’s automatic escaping converts special characters to HTML entities. For instance, if $user->name contains <script>alert('hack');</script>, it’s rendered as plain text, not executable code.

To bypass escaping (use with caution), use {!! !!}:

<div>{!! $user->bio !!}</div>

This is useful for rendering HTML content but risks XSS if the input isn’t sanitized.

Using Raw Output with Triple Curly Braces

For trusted content, Blade supports {{{ $variable }}}, which is equivalent to {{ html_entity_decode($variable) }}. However, this is less common and should be avoided unless necessary.

Blade Directives for Dynamic Data

Blade provides directives like @php and @isset for dynamic data handling:

  • @php: Embeds raw PHP code.

  • @isset: Checks if a variable is set before displaying it.

Example:

@php
    $greeting = 'Hello, ' . $user->name;
@endphp
<p>{{ $greeting }}</p>

@isset($user->email)
    <p>Email: {{ $user->email }}</p>
@endisset

Pros and Cons

Pros:

  • Secure by Default: Automatic escaping prevents XSS vulnerabilities.

  • Concise Syntax: {{ }} is more readable than PHP’s <?php echo ?>.

  • Flexible Directives: @php, @isset, and others simplify dynamic data handling.

Cons:

  • Overuse of Raw Output: Using {!! !!} can introduce security risks.

  • Template Clutter: Excessive logic in templates can reduce maintainability.

Alternatives

  • Plain PHP: Use <?php echo htmlspecialchars($variable); ?> for manual escaping.

  • Twig: Offers similar escaping but with a steeper learning curve.

  • Vue.js/React: Dynamic data binding with JavaScript frameworks, though they require client-side processing.

Best Practices

  • Always Use {{ }} for User Input: Prevents XSS attacks.

  • Sanitize Raw Output: Use Laravel’s Purifier package for {!! !!} content.

  • Keep Templates Clean: Move complex logic to controllers or helpers.

  • Use @isset or @empty: Prevent undefined variable errors.

Example: Building a User Profile Page

Let’s create a user profile page that displays dynamic data for a social media application.

Step 1: Define a RouteIn routes/web.php:

use App\Models\User;
use Illuminate\Support\Facades\Route;

Route::get('/profile/{id}', function ($id) {
    $user = User::findOrFail($id);
    return view('profile', [
        'user' => $user,
        'posts' => ['Post 1', 'Post 2', 'Post 3']
    ]);
});

Step 2: Create the Blade TemplateIn resources/views/profile.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>{{ $user->name }}'s Profile</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <div class="container mx-auto p-6">
        <h1 class="text-4xl font-bold">{{ $user->name }}'s Profile</h1>
        @isset($user->bio)
            <p class="mt-4 text-lg">{{ $user->bio }}</p>
        @else
            <p class="mt-4 text-gray-500">No bio available.</p>
        @endisset

        <h2 class="mt-6 text-2xl font-semibold">Recent Posts</h2>
        @if(count($posts) > 0)
            <ul class="mt-4 list-disc pl-6">
                @foreach($posts as $post)
                    <li>{{ $post }}</li>
                @endforeach
            </ul>
        @else
            <p class="mt-4 text-gray-500">No posts yet.</p>
        @endif

        @php
            $joined = 'Joined: ' . $user->created_at->format('M d, Y');
        @endphp
        <p class="mt-6 text-sm text-gray-600">{{ $joined }}</p>
    </div>
</body>
</html>

Step 3: Explanation

  • Dynamic Data: {{ $user->name }} and {{ $user->bio }} display user data.

  • Conditional Logic: @isset checks for a bio, and @if checks for posts.

  • PHP Directive: @php formats the join date.

  • Styling: Tailwind CSS ensures a modern, responsive design.

Output: A clean profile page showing the user’s name, bio, posts, and join date, with fallbacks for missing data.


3. Blade Control Structures (@if, @foreach)

Conditional Rendering with @if, @elseif, @else

Blade’s @if, @elseif, and @else directives simplify conditional logic in templates, replacing PHP’s if statements with a cleaner syntax.

Example:

@if($user->is_admin)
    <p class="text-green-600">Welcome, Admin!</p>
@elseif($user->is_premium)
    <p class="text-blue-600">Welcome, Premium User!</p>
@else
    <p class="text-gray-600">Welcome, Guest!</p>
@endif

Looping with @foreach, @forelse

The @foreach directive iterates over arrays or collections, while @forelse adds an empty state handler.

Example:

@forelse($products as $product)
    <div>{{ $product->name }} - ${{ $product->price }}</div>
@empty
    <p>No products available.</p>
@endforelse

Other Control Structures (@while, @unless)

  • @while: Loops while a condition is true.

  • @unless: Executes if a condition is false.

Example:

@unless($user->is_active)
    <p>Your account is inactive.</p>
@endunless

@while($count < 5)
    <p>Count: {{ $count }}</p>
    @php $count++ @endphp
@endwhile

Pros and Cons

Pros:

  • Readable Syntax: Directives are more concise than raw PHP.

  • Built-in Empty State: @forelse simplifies handling empty collections.

  • Flexible Conditions: Supports complex logic with minimal code.

Cons:

  • Logic Overload: Overusing control structures can clutter templates.

  • Debugging: Errors in Blade directives can be harder to trace than PHP.

Alternatives

  • Raw PHP: Use <?php if() {} ?> for conditions, though less elegant.

  • Vue.js/React: Use JavaScript-based conditionals for client-side rendering.

  • Twig: Offers similar control structures but requires integration with Laravel.

Best Practices

  • Limit Logic: Move complex conditions to controllers or models.

  • Use @forelse for Collections: Handles empty states gracefully.

  • Test Conditions: Ensure variables are defined to avoid errors.

  • Follow PSR-2: Maintain consistent code style.

Example: Displaying a Product Listing

Let’s build a product listing page for an e-commerce site.

Step 1: Define a RouteIn routes/web.php:

use App\Models\Product;
use Illuminate\Support\Facades\Route;

Route::get('/products', function () {
    $products = Product::all();
    return view('products', ['products' => $products]);
});

Step 2: Create the Blade TemplateIn resources/views/products.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Our Products</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <div class="container mx-auto p-6">
        <h1 class="text-4xl font-bold mb-6">Product Listing</h1>
        @forelse($products as $product)
            <div class="bg-white p-4 mb-4 rounded shadow">
                <h2 class="text-xl font-semibold">{{ $product->name }}</h2>
                <p class="text-gray-600">${{ $product->price }}</p>
                @if($product->in_stock)
                    <span class="text-green-600">In Stock</span>
                @else
                    <span class="text-red-600">Out of Stock</span>
                @endif
            </div>
        @empty
            <p class="text-gray-500">No products available.</p>
        @endforelse
    </div>
</body>
</html>

Step 3: Explanation

  • @forelse: Loops through products and handles the empty case.

  • @if: Displays stock status conditionally.

  • Tailwind CSS: Provides a responsive, card-based layout.

  • Dynamic Data: Displays product name and price from the database.

Output: A clean product listing with stock status indicators, styled professionally.


4. Layouts & Sections

Template Inheritance with @extends

Blade’s @extends directive allows a child template to inherit a parent layout, promoting code reuse. The parent layout uses @yield to define placeholders for content.

Example:

<!-- resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html>
<head>
    <title>@yield('title', 'My App')</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <header class="bg-blue-600 text-white p-4">
        <h1>My Blog</h1>
    </header>
    <div class="container mx-auto p-6">
        @yield('content')
    </div>
    <footer class="bg-gray-800 text-white p-4 text-center">
        &copy; 2025 My Blog
    </footer>
</body>
</html>

Child template:

<!-- resources/views/home.blade.php -->
@extends('layouts.app')
@section('title', 'Home Page')
@section('content')
    <h2>Welcome to My Blog</h2>
    <p>Explore our latest posts!</p>
@endsection

Defining and Yielding Sections

Sections are defined with @section and rendered with @yield. Use @show to immediately render a section in the layout.

Example:

<!-- resources/views/layouts/app.blade.php -->
@section('sidebar')
    <div class="sidebar">Default Sidebar</div>
@show

Using @parent for Extending Content

The @parent directive appends content to a parent section.

Example:

<!-- resources/views/child.blade.php -->
@extends('layouts.app')
@section('sidebar')
    @parent
    <p>Additional sidebar content.</p>
@endsection

Pros and Cons

Pros:

  • Code Reusability: Layouts eliminate repetitive HTML.

  • Consistency: Ensures uniform design across pages.

  • Flexibility: @parent allows extending existing sections.

Cons:

  • Complexity in Large Projects: Nested layouts can become hard to manage.

  • Learning Curve: Understanding @yield vs. @section takes practice.

Alternatives

  • Plain PHP Includes: Use <?php include 'header.php'; ?> but less dynamic.

  • Twig Layouts: Similar inheritance but requires Symfony integration.

  • Vue.js/React Components: Offer reusable layouts but require JavaScript.

Best Practices

  • Use a Single Master Layout: Centralize common elements like headers and footers.

  • Keep Layouts Simple: Avoid heavy logic in layout files.

  • Organize Files: Store layouts in resources/views/layouts/.

  • Use Descriptive Section Names: Improve readability (e.g., @section('content')).

Example: Creating a Blog Layout

Let’s create a blog layout with a sidebar and dynamic content.

Step 1: Create the LayoutIn resources/views/layouts/blog.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>@yield('title', 'My Blog')</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <header class="bg-blue-600 text-white p-4">
        <h1>My Blog</h1>
    </header>
    <div class="container mx-auto p-6 flex">
        <aside class="w-1/4 p-4 bg-white rounded shadow">
            @yield('sidebar', 'Default Sidebar Content')
        </aside>
        <main class="w-3/4 p-4">
            @yield('content')
        </main>
    </div>
    <footer class="bg-gray-800 text-white p-4 text-center">
        &copy; 2025 My Blog
    </footer>
</body>
</html>

Step 2: Create a Post PageIn resources/views/post.blade.php:

@extends('layouts.blog')
@section('title', 'Blog Post')
@section('sidebar')
    <h3>Categories</h3>
    <ul class="list-disc pl-6">
        <li>Technology</li>
        <li>Lifestyle</li>
        <li>Travel</li>
    </ul>
@endsection
@section('content')
    <h2>{{ $post->title }}</h2>
    <p>{{ $post->content }}</p>
@endsection

Step 3: Define a RouteIn routes/web.php:

use App\Models\Post;
use Illuminate\Support\Facades\Route;

Route::get('/post/{id}', function ($id) {
    $post = Post::findOrFail($id);
    return view('post', ['post' => $post]);
});

Step 4: Explanation

  • @extends: Inherits the blog layout.

  • @section: Defines sidebar and content sections.

  • @yield: Renders dynamic content with a fallback title.

  • Tailwind CSS: Creates a responsive two-column layout.

Output: A blog post page with a consistent header, footer, and sidebar, styled professionally.


5. Components & Slots

Creating Reusable Components

Blade components are reusable UI elements defined as classes or anonymous templates. They simplify complex views and promote modularity.

Step 1: Create a ComponentRun:

php artisan make:component Alert

This generates app/View/Components/Alert.php and resources/views/components/alert.blade.php.

Step 2: Define the ComponentIn app/View/Components/Alert.php:

namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
    public $type;
    public $message;

    public function __construct($type, $message)
    {
        $this->type = $type;
        $this->message = $message;
    }

    public function render()
    {
        return view('components.alert');
    }
}

In resources/views/components/alert.blade.php:

<div class="p-4 rounded {{ $type === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' }}">
    {{ $message }}
</div>

Step 3: Use the ComponentIn any Blade template:

<x-alert type="success" message="Operation successful!" />
<x-alert type="error" message="Something went wrong." />

Using Slots for Flexible Content

Slots allow components to accept dynamic content. The default slot is $slot, and named slots can be defined.

Example:

<!-- resources/views/components/card.blade.php -->
<div class="bg-white p-6 rounded shadow">
    <h2 class="text-xl font-semibold">{{ $title }}</h2>
    <div class="mt-4">
        {{ $slot }}
    </div>
    @isset($footer)
        <div class="mt-4 text-gray-600">
            {{ $footer }}
        </div>
    @endisset
</div>

Usage:

<x-card title="Product Card">
    <p>This is the card content.</p>
    <x-slot name="footer">
        <p>Footer content here.</p>
    </x-slot>
</x-card>

Component Attributes and Props

Components can accept attributes (props) for customization. Use the $attributes bag to access HTML attributes.

Example:

<!-- resources/views/components/button.blade.php -->
<button {{ $attributes->merge(['class' => 'bg-blue-600 text-white p-2 rounded']) }}>
    {{ $slot }}
</button>

Usage:

<x-button class="hover:bg-blue-800">Click Me</x-button>

Pros and Cons

Pros:

  • Modularity: Components promote reusable UI elements.

  • Flexibility: Slots allow dynamic content injection.

  • Maintainability: Encapsulates logic for easier updates.

Cons:

  • Initial Setup: Creating components requires additional steps.

  • Overuse: Too many components can overcomplicate simple projects.

Alternatives

  • Blade Includes: Use @include for simple reusable parts.

  • Vue.js/React Components: More powerful for dynamic UIs but require JavaScript.

  • Livewire Components: Blade-based with server-side reactivity.

Best Practices

  • Use Descriptive Names: Name components clearly (e.g., alert, card).

  • Keep Components Focused: Follow the single responsibility principle.

  • Leverage Slots: Use named slots for flexible content.

  • Test Components: Ensure components work across contexts.

Example: Building a Reusable Card Component

Let’s create a card component for a dashboard.

Step 1: Create the Component

php artisan make:component DashboardCard

Step 2: Define the ComponentIn app/View/Components/DashboardCard.php:

namespace App\View\Components;

use Illuminate\View\Component;

class DashboardCard extends Component
{
    public $title;
    public $value;

    public function __construct($title, $value)
    {
        $this->title = $title;
        $this->value = $value;
    }

    public function render()
    {
        return view('components.dashboard-card');
    }
}

In resources/views/components/dashboard-card.blade.php:

<div class="bg-white p-6 rounded shadow">
    <h3 class="text-lg font-semibold">{{ $title }}</h3>
    <p class="text-2xl mt-2">{{ $value }}</p>
    {{ $slot }}
</div>

Step 3: Use in a DashboardIn resources/views/dashboard.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <div class="container mx-auto p-6 grid grid-cols-3 gap-4">
        <x-dashboard-card title="Total Users" value="1,234">
            <p class="text-gray-600">Updated today</p>
        </x-dashboard-card>
        <x-dashboard-card title="Revenue" value="$5,678">
            <p class="text-gray-600">This month</p>
        </x-dashboard-card>
        <x-dashboard-card title="Orders" value="89">
            <p class="text-gray-600">Pending</p>
        </x-dashboard-card>
    </div>
</body>
</html>

Step 4: Define a RouteIn routes/web.php:

Route::get('/dashboard', function () {
    return view('dashboard');
});

Step 5: Explanation

  • Component: Displays a title, value, and optional slot content.

  • Grid Layout: Tailwind CSS creates a responsive three-column dashboard.

  • Reusability: The card can be used for various metrics.

Output: A dashboard with three cards showing user count, revenue, and orders, styled cleanly.


6. Conditional Rendering & Loops

Advanced Conditional Rendering Techniques

Combine @if, @unless, and @switch for complex logic.

Example:

@switch($user->role)
    @case('admin')
        <p>Admin Dashboard</p>
        @break
    @case('user')
        <p>User Dashboard</p>
        @break
    @default
        <p>Guest Dashboard</p>
@endswitch

Nested Loops and Conditional Logic

Nested @foreach loops handle hierarchical data, like categories and subcategories.

Example:

@foreach($categories as $category)
    <h2>{{ $category->name }}</h2>
    <ul>
        @foreach($category->products as $product)
            <li>{{ $product->name }} - ${{ $product->price }}</li>
        @endforeach
    </ul>
@endforeach

Optimizing Performance in Loops

  • Use Eager Loading: Prevent N+1 query issues with with() in Eloquent.

  • Cache Data: Use Laravel’s caching for frequently accessed data.

  • Limit Iterations: Paginate large datasets to reduce rendering time.

Pros and Cons

Pros:

  • Expressive Logic: Simplifies complex rendering scenarios.

  • Integration with Eloquent: Works seamlessly with Laravel’s ORM.

  • Readability: Cleaner than nested PHP loops.

Cons:

  • Performance Risk: Heavy loops can slow down rendering.

  • Complexity: Nested logic can make templates harder to maintain.

Alternatives

  • Raw PHP Loops: More control but less readable.

  • Vue.js/React Loops: Client-side rendering for dynamic UIs.

  • Livewire: Server-side rendering with Blade-like syntax.

Best Practices

  • Paginate Large Datasets: Use Laravel’s pagination for loops.

  • Eager Load Relationships: Avoid N+1 query issues.

  • Keep Logic Simple: Move complex logic to controllers or models.

  • Use @forelse: Handle empty collections gracefully.

Example: E-commerce Product Filtering System

Let’s build a product filtering system with categories and price ranges.

Step 1: Define a RouteIn routes/web.php:

use App\Models\Product;
use App\Models\Category;
use Illuminate\Support\Facades\Route;

Route::get('/shop', function () {
    $categories = Category::with('products')->get();
    $priceRanges = [
        ['label' => 'Under $50', 'min' => 0, 'max' => 50],
        ['label' => '$50-$100', 'min' => 50, 'max' => 100],
        ['label' => 'Over $100', 'min' => 100, 'max' => null]
    ];
    return view('shop', [
        'categories' => $categories,
        'priceRanges' => $priceRanges
    ]);
});

Step 2: Create the Blade TemplateIn resources/views/shop.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Shop</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <div class="container mx-auto p-6">
        <h1 class="text-4xl font-bold mb-6">Shop Our Products</h1>
        <div class="flex">
            <aside class="w-1/4 p-4 bg-white rounded shadow">
                <h3 class="text-lg font-semibold">Filters</h3>
                <h4 class="mt-4">Categories</h4>
                @foreach($categories as $category)
                    <div>
                        <input type="checkbox" id="category-{{ $category->id }}">
                        <label for="category-{{ $category->id }}">{{ $category->name }}</label>
                    </div>
                @endforeach
                <h4 class="mt-4">Price Ranges</h4>
                @foreach($priceRanges as $range)
                    <div>
                        <input type="checkbox" id="price-{{ $loop->index }}">
                        <label for="price-{{ $loop->index }}">{{ $range['label'] }}</label>
                    </div>
                @endforeach
            </aside>
            <main class="w-3/4 p-4">
                @forelse($categories as $category)
                    <h2 class="text-2xl font-semibold">{{ $category->name }}</h2>
                    @foreach($category->products as $product)
                        <div class="bg-white p-4 mb-4 rounded shadow">
                            <h3 class="text-lg">{{ $product->name }}</h3>
                            <p>${{ $product->price }}</p>
                            @if($product->price < 50)
                                <span class="text-green-600">Budget Friendly</span>
                            @elseif($product->price <= 100)
                                <span class="text-blue-600">Mid-Range</span>
                            @else
                                <span class="text-purple-600">Premium</span>
                            @endif
                        </div>
                    @endforeach
                @empty
                    <p class="text-gray-500">No products available.</p>
                @endforelse
            </main>
        </div>
    </div>
</body>
</html>

Step 3: Explanation

  • Nested Loops: Displays categories and their products.

  • Conditional Rendering: Tags products by price range.

  • Filters: Checkboxes for categories and price ranges (client-side logic can be added later).

  • Tailwind CSS: Creates a responsive two-column layout.

Output: A shop page with filterable products, styled professionally and optimized for usability.


7. Conclusion

Recap of Blade’s Power

Blade is a cornerstone of Laravel’s ecosystem, offering a balance of simplicity, power, and performance. From basic data display to complex components and layouts, Blade empowers developers to create dynamic, maintainable views. Its elegant syntax, combined with features like template inheritance, control structures, and reusable components, makes it ideal for projects of all sizes.

No comments:

Post a Comment

Thanks for your valuable comment...........
Md. Mominul Islam

Post Bottom Ad

Responsive Ads Here