Your Guide to Laravel Excellence

How to show old selected values in multiple select options in Laravel

How to show old selected values in multiple select options in Laravel

When creating a form to manage posts and their associated categories, especially with a many-to-many relationship, it's important to show previously selected categories. This ensures users can see and manage their current selections when updating a post.

Below is a refined approach to achieve this in a Laravel Blade template.


<div class="mb-3">
    <label class="form-label" for="category">Category</label>
    <select class="form-control" id="category" name="category_id[]" multiple>
        @foreach ($categories as $category)
            <option value="{{ $category->id }}"
                {{ in_array($category->id, $post?->categories->pluck('id')->toArray() ?? []) ? 'selected' : '' }}>
                {{ $category->name }}
            </option>
        @endforeach
    </select>
    @error('category_id')
        <span class="pt-3 text-danger">{{ $message }}</span>
    @enderror
</div>

Benefits of This Approach

Clarity: Clearly shows which categories are selected based on the post object.

Flexibility: Handles both creating and updating posts with selected categories.

Error Display: Properly shows validation errors related to category selection.

Recommeded Posts

How to Add Real-Time Comments in Laravel 11 with Laravel Reverb

How to Add Real-Time Comments in Laravel 11 with Laravel Reverb

How to Add Real-Time Comments in Laravel 11 with Laravel Reverb

2 months ago Read article →
How to Create XML from an Array Using Spatie(array-to-xml) in Laravel

How to Create XML from an Array Using Spatie(array-to-xml) in Laravel

Learn how to convert an array into XML format using the Spatie array-to-xml package in Laravel. This easy guide walks you through the steps to set up the package and create XML files from your data quickly.

2 months ago Read article →
Convert mp4 to m3u8 using FFMpeg for Laravel with AWS S3

Convert mp4 to m3u8 using FFMpeg for Laravel with AWS S3

Convert mp4 to m3u8 using FFMpeg for Laravel with AWS S3

2 months ago Read article →
Guide to Session Management and Flash Messages in Laravel

Guide to Session Management and Flash Messages in Laravel

Learn how to use Laravel's session management and flash messages. This comprehensive guide covers storing data, handling user states, and displaying temporary notifications in your Laravel applications.

2 months ago Read article →