Sling Academy
Home/PHP/Laravel: Rendering a table with PHP array data in Blade

Laravel: Rendering a table with PHP array data in Blade

Last updated: January 15, 2024

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.

Next Article: Laravel Blade: How to show a view only to logged-in users

Previous Article: Laravel Blade: How to Enable Auto-completion in VS Code

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array