Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skreng's avatar

How to make selected in form when edit

Hi! I have problem with quite easy thing. But I probably to dumb to finde antwser in documentation.

I have relation 1=>N (One user can be assign with multiple roles). In User model it's tandard relation

    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class);
    }

On livewire level value of response looks like

[{"id":3,"name":"trainer","created_at":"2022-11-01T19:59:49.000000Z","updated_at":"2022-11-01T19:59:49.000000Z","pivot":{"user_id":6,"role_id":3}},{"id":4,"name":"user","created_at":"2022-11-01T19:59:49.000000Z","updated_at":"2022-11-01T19:59:49.000000Z","pivot":{"user_id":6,"role_id":4}}] 

How on blade level I can make selected thoes multiple select field?

<select multiple name="role[]" wire:model.defer="user.role"
                class="rounded-md shadow-sm border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            @foreach($roles as $role)
                <option value="{{ $role->id }}">
                    {{ Str::ucfirst($role->name) }}
            </option>
            @endforeach
        </select>
0 likes
7 replies
wagnerfnds's avatar

did you tried wire:model.defer="user.roles()" or user.roles?

skreng's avatar

@wagnerfnds Yes but non of the options are selected. I even check Chrome inspection.

jlrdw's avatar

@skreng you have to tell it which one is selected from what is stored in the database.

Just FYI has been covered before in previous post.

MohamedTammam's avatar

In your Livewire add

$selectedRolesIDs = $user->roles->pluck('id')->all();

In your blade

<option value="{{ $role->id }}" @selected(in_array($role->id, $selectedRolesIDs))>
wagnerfnds's avatar
Level 9

@MohamedTammam when you have an array of ids as a model of the select element, you dont really need to check if its contain id on the option element to make it selected, livewire does that for you, so in this case him could use like that:

initialize the model var

public $selectedRolesIDs = [];

and render it with the ids like you did

$selectedRolesIDs = $user->roles->pluck('id')->all();

then in blade pass $selectedRolesIDs as a model

< select multiple name="roles[]" wire:model.defer="selectedRolesIDs" >

pretty sure this will works

1 like
Snapey's avatar

Setup an array in the component as public property and wire model it to the select input. You don't need to check the option in the view.

skreng's avatar

@Snapey Can you show me on my example? Couse I don't understand how public array can be connected with relation on the model. Sorry for silly question but i'm new on the Livewire.

Please or to participate in this conversation.