Sling Academy
Home/PHP/Laravel + Blade: How to Create a “Table of Contents”

Laravel + Blade: How to Create a “Table of Contents”

Last updated: January 26, 2024

Introduction

Creating a Table of Contents (TOC) in any document or web page aids in navigating through the content effectively. For web applications built on Laravel with Blade templating, generating a TOC dynamically can greatly enhance user experience. In this tutorial, we will guide you through the process of creating a dynamic Table of Contents in Laravel using Blade.

Prerequisites

  • Basic understanding of PHP and Laravel.
  • Laravel Framework installed (version 8 or higher is recommended).
  • Basic knowledge of HTML and CSS.
  • Composer package manager installed.

Setting Up Your Laravel Project

// Create a new Laravel project
echoamberlane:
cdvoid:

To begin, ensure that you have a Laravel project already set up. This can be achieved simply with the following command:

composer create-project --prefer-dist laravel/laravel your-project-name After the project is created, navigate to the project directory: cd your-project-name 

Understanding Blade Templating

In Laravel, Blade is the default templating engine that allows you to write template files using plain PHP code which is both expressive and powerful. Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application.

Creating Layout and Content View

Firstly, let’s create the main layout file which establishes the basic structure for our web page. Within your Laravel application, Blade templates are stored in the resources/views directory. We’ll start by creating a master layout called layout.blade.php.

<!-- resources/views/layout.blade.php -->
<!DOCTYPE html>
<html>
<head>
  <title>Your Application Name</title>
</head>
<body>

  @yield('content')

</body>
</html>

In the master layout, we have included a @yield directive. The @yield directive is a placeholder for content and will be filled when using the layout as the base for other views.

Next, we will create a content view that utilizes the master layout. Let’s scaffold a table of contents and the content sections using Blade’s @section directive. Create a new view file named content.blade.php.

<!-- resources/views/content.blade.php -->
@extends('layout')

@section('content')
<div>
  <!-- Table of Contents -->
  <div id="table-of-contents">
    <h2>Table of Contents</h2>
    <ul>
      @foreach($sections as $section)
        <li>
          <a href="#{{ $section['id'] }}">{{ $section['title'] }}</a>
        </li>
      @endforeach
    </ul>
  </div>

  <!-- Content Sections -->
  <div id="content-sections">
    @foreach($sections as $section)
      <div id="{{ $section['id'] }}">
        <h2>{{ $section['title'] }}</h2>
        <p>{{ $section['content'] }}</p>
      </div>
    @endforeach
  </div>
</div>

@endsection

The @foreach directive is used here to iterate through an array of sections that we will pass to the view from a controller.

Creating Controller and Routes

Create a new controller named ContentController.php using the artisan command:

php artisan make:controller ContentController

In the controller, define a method that will return the view with the contents for generating the TOC:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ContentController extends Controller
{
  public function index()
  {
    $sections = [
      ['id' => 'section-1', 'title' => 'Introduction', 'content' => '...'],
      ['id' => 'section-2', 'title' => 'Getting Started', 'content' => '...'],
      // more sections
    ];

    return view('content', compact('sections'));
  }
}

Update your routes file at routes/web.php to include the content route:

use App\Http\Controllers\ContentController;

Route::get('/contents', [ContentController::class, 'index']);

Styling the Table of Contents

Style your Table of Contents with CSS for better visualization. Below is a basic styling which you can add in thesection of your layout file or external stylesheet.

#table-of-contents {
  margin-bottom: 20px;
}

code:
#content-sections {
  background: #eee;
  padding: 20px;
}

#table-of-contents ul {
  list-style: none;
}

#table-of-contents li a {
  text-decoration: none;
  color: blue;
}

#content-sections div {
  margin-bottom: 20px;
}

Include the stylesheet applied to make the TOC more presentable by either linking it in the head tag of your layout or by using the @push and @stack directives for inline styles.

Conclusion

With the above steps, you can create a functioning Table of Contents for your Laravel application using Blade templating. This TOC will dynamically generate based on the contents provided, allowing you to manage content sections easily without manual updates to your TOC. Remember to apply proper IDs and maintain a structure that can be easily scaled for future content additions.

Following best practices in Blade templating and Laravel, you have now created a TOC that can be reused across different views, making your application more modular and maintainable.

Next Article: How to connect to SQLite database in Laravel

Previous Article: How to Execute SQL Queries in Laravel

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