Laravel: Rendering a table with PHP array data in Blade

Updated: January 15, 2024 By: Guest Contributor Post a comment

Introduction

Laravel Blade is a powerful templating engine provided with Laravel, which makes tasks like rendering HTML tables from PHP arrays an intuitive and easy process. In this tutorial, we will guide you through the basic to advanced steps of displaying PHP array data as a table in a Blade view. Understanding this concept is crucial for developers looking to display structured data within their Laravel applications.

Setting Up the Controller

Before getting to Blade, let’s setup our controller with dummy data.

<?php

namespace App\Http\Controllers;

class TableController extends Controller
{
    public function index()
    {
        $data = [
            ['id' => 1, 'name' => 'John', 'email' => '[email protected]'],
            ['id' => 2, 'name' => 'Jane', 'email' => '[email protected]'],
            //... other records
        ];

        return view('table', compact('data'));
    }
}

Basic Table Rendering

Now, let’s focus on the Blade view called table.blade.php.

<!-- resources/views/table.blade.php -->
<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        @foreach($data as $row)
            <tr>
                <td>{{ $row['id'] }}</td>
                <td>{{ $row['name'] }}</td>
                <td>{{ $row['email'] }}</td>
            </tr>
        @endforeach
    </tbody>
</table>

This basic example simply loops through each element in the $data array passed from the controller and displays it within table row and data cells.

Enhancing with Bootstrap

We can now enhance our table’s appearance by including the Bootstrap framework.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet">

<table class="table">
    <!-- Table Content -->
</table>

Adding Sorting Capabilities

Following the principles of progressive enhancement, let’s add sorting capabilities to our table headings. We’ll continue from the Bootstrap-enhanced table.

<!-- Additional sorting feature, not implemented in actual code here -->
<th>
    <a href="?sortby=id&order=asc">ID</a>
</th>
<!-- Other table headers -->

This snippet suggests front-end changes, showing how you might structure links for sorting; implementing the sorting logic in the controller is beyond the scope of this visual example.

Paginating Table Data

Laravel’s paginator is a breeze to use in Blade. Here’s an adjusted controller method to apply pagination:

public function index()
{
    $data = User::paginate(10); // Eloquent model example
    return view('table', compact('data'));
}

And in the Blade view, you’d render the paginator like this:

<!-- Table as above -->

<div class="text-center">
    {{ $data->links() }}
</div>

Handling Empty Data Sets

When there’s a possibility that no data will be returned, gracefully handling an empty state is essential.

<tbody>
    @forelse ($data as $row)
        <!-- Table rows -->
    @empty
        <tr>
            <td colspan="3">No records found.</td>
        </tr>
    @endforelse
</tbody>

Advanced Column Customization

With more complex data structures, you may want to selectively display information. Blade’s templating features make this easy.

<tr>
    <td>{{ $row['id'] }}</td>
    <!-- More columns -->
    <td>
        <button class="btn btn-primary">View</button>
    </td>
</tr>

You can insert any HTML or Blade directive to customize each column’s rendering.

Conclusion

Through this tutorial, we’ve seen how Laravel’s Blade makes it simple to render tables from PHP arrays and progressively enhance them with features like pagination, sorting, and bootstrap styling. Effective rendering and presentation of data lays the foundation for building user-friendly web applications in Laravel.