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

Building RESTful APIs in Laravel 11: A Simple Guide

Building RESTful APIs in Laravel 11: A Simple Guide

Building RESTful APIs in Laravel 11: A Simple Guide

4 months ago Read article →
Faster Query with `whereIntegerInRaw` Method

Faster Query with `whereIntegerInRaw` Method

Faster Query with `whereIntegerInRaw` Method

4 months ago Read article →
How to Prevent Spam in Laravel Forms with spatie/laravel-honeypot

How to Prevent Spam in Laravel Forms with spatie/laravel-honeypot

How to Prevent Spam in Laravel Forms with spatie/laravel-honeypot

4 months ago Read article →
Multi language in laravel 11

Multi language in laravel 11

Multi language in laravel 11

4 months ago Read article →