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

Infinite Scroll in Laravel Using jQuery and AJAX

Infinite Scroll in Laravel Using jQuery and AJAX

Infinite Scroll in Laravel Using jQuery and AJAX

3 months ago Read article →
Differences Between Cron Jobs and Laravel Scheduler

Differences Between Cron Jobs and Laravel Scheduler

Differences Between Cron Jobs and Laravel Scheduler

3 months ago Read article →
Better Error Handling with onFailure Callback in Laravel's DB::transaction() (New in Laravel 12.9)

Better Error Handling with onFailure Callback in Laravel's DB::transaction() (New in Laravel 12.9)

Laravel 12.9 now supports onFailureCallback in DB::transaction(), making database error handling easier with automatic rollback and failure notifications.

3 months ago Read article →
Laravel Tip: The "whereKey" Method

Laravel Tip: The "whereKey" Method

Laravel Tip: The "whereKey" Method

3 months ago Read article →