Sling Academy
Home/PHP/Laravel Blade: Rendering a list of dynamic checkboxes

Laravel Blade: Rendering a list of dynamic checkboxes

Last updated: January 15, 2024

Introduction

Laravel Blade is the templating engine that comes bundled with Laravel, a popular PHP framework. Blade provides a convenient and expressive way of working with PHP code in your views. In this tutorial, we’ll focus on how to render a list of dynamic checkboxes using Blade.

Checkboxes are a critical component of web forms where multiple selections are possible. Suppose you’re building a web application that needs to capture user interests or roles. These are typical scenarios where dynamic checkboxes can come into play.

Getting Started

Before diving into the Blade syntax and dynamic checkbox generation, ensure you have a working Laravel installation. You can create a new Laravel project by using Composer:

$ composer create-project --prefer-dist laravel/laravel checkboxApp

After the installation is complete, navigate to your application’s root directory:

$ cd checkboxApp

Now let’s create a simple route, controller, and view to render our checkboxes.

Basic Checkboxes

If you’re new to Laravel, first create a controller using the Artisan CLI:

$ php artisan make:controller CheckboxController

In the newly created CheckboxController.php, add a function that returns a view with some dummy data for the checkboxes:

public function index()
{
    $interests = [
        'coding' => 'Coding',
        'music' => 'Music',
        'sports' => 'Sports',
    ];
    
    return view('checkboxes.index', compact('interests'));
}

Now, in your resources/views directory, create the checkboxes folder and inside it an index.blade.php file:

In index.blade.php, you’d loop through the interests and create a checkbox for each:

<form action="" method="post">
    @csrf
    @foreach ($interests as $key => $value)
        <label>
            <input type="checkbox" name="interests[]" value="{{ $key }}"> {{ $value }}
        </label>
    @endforeach
    <button type="submit">Submit</button>
</form>

Pre-selecting Checkboxes

Often, you want to pre-select checkboxes based on user preference or other criteria. Here’s how you can do that:

@foreach ($interests as $key => $value)
    <label>
        <input type="checkbox" name="interests[]" value="{{ $key }}" {{ in_array($key, $userInterests) ? 'checked' : '' }}> {{ $value }}
    </label>
@endforeach

Here, $userInterests could be an array of interests fetched from the database representing the user’s previously selected interests.

Advanced Usage with Models

Let’s take it up a notch by involving Eloquent models. Suppose you have a User model and a Interest model. You want to display a list of checkboxes of all interests and mark the user’s interests as checked:

In your CheckboxController add a new method for the advanced view:

public function advancedIndex(User $user)
{
    $interests = Interest::all();
    $userInterests = $user->interests()->pluck('interests.id')->toArray();

    return view('checkboxes.advanced', compact('interests', 'userInterests'));
}

In the advanced.blade.php view, the checkbox creation becomes:

@foreach ($interests as $interest)
    <label>
        <input type="checkbox" name="interests[]" value="{{ $interest->id }}" {{ in_array($interest->id, $userInterests) ? 'checked' : '' }}> {{ $interest->name }}
    </label>
@endforeach

Conclusion

In this tutorial, we’ve walked through the basics of rendering dynamic checkboxes in a Laravel Blade view all the way to utilizing Eloquent models for more advanced scenarios. Harnessing Blade’s templating power enables you to build robust and user-friendly forms with ease.

Next Article: Laravel: Render links with dynamic href attributes in Blade

Previous Article: Laravel Blade: Using ‘@yield’ and ‘@section’ directives

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