Search code examples
phplaraveladminlte

How to load items in AdminLte multi select dropdown for update - Laravel 8


I have a ClassController which sends $players & $classPlayers collections to a view.

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $classe = Classe::findOrFail($id);
    $players = User::whereRoleIs(['player'])->get();
    $classePlayers = User::where('classe_id', '=', $classe->id)->get();
    
    return view("admin.classes.edit", compact('classe', 'players', 'classePlayers'));
}

the collection $players contains one to many players:

  #items: array:6 [▼
    0 => App\Models\User {#1338 ▼
      #fillable: array:4 [▼
        0 => "name"
        1 => "email"
        2 => "password"
        3 => "matricule"
      ]
      #hidden: array:2 [▶]
      #casts: array:1 [▶]
      #connection: "mysql"
      #table: "users"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:10 [▶]
      #original: array:10 [▶]
      #changes: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #visible: []
      #guarded: array:1 [▶]
      #rememberTokenName: "remember_token"
    }

and the collection $classPlayers contain the players of a class (One to Many relationship)

Illuminate\Database\Eloquent\Collection {#1331 ▼
  #items: array:4 [▼
    0 => App\Models\User {#1324 ▶}
    1 => App\Models\User {#1335 ▼
      #fillable: array:4 [▶]
      #hidden: array:2 [▶]
      #casts: array:1 [▶]
      #connection: "mysql"
      #table: "users"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:10 [▼
        "id" => 5
        "name" => "Joueur X"
        "email" => "joueur.x@gmail.com"
        "email_verified_at" => "2021-07-28 20:04:40"
        "password" => "$2y$10$MWA6G0PjV4qm0ZVgyB3MQO0Sn2x1IN3.W9zPwIljKNwQms4eaTaEm"
        "remember_token" => "BI7R6Zw1HV"
        "created_at" => null
        "updated_at" => "2021-07-29 01:26:29"
        "matricule" => "XYZ"
        "classe_id" => 13
      ]
      #original: array:10 [▶]
      #changes: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #visible: []
      #guarded: array:1 [▶]
      #rememberTokenName: "remember_token"
    }
    2 => App\Models\User {#1346 ▶}
    3 => App\Models\User {#1347 ▶}
  ]
}

I want to show the list of all players and make the players within classPlayers selected.

I tried something like that:

                                    <select class="selectPlayers @error('players') is-invalid @enderror" id="players"
                                        name="players[]" multiple="multiple" style="width: 100%;">
                                        @foreach($classePlayers as $player)
                                        <option value="{{$player->id}}" {{ in_array($player->id, $players->toArray()) ? "selected": ""}}>
                                            {{ $player->name }}
                                        </option>
                                        @endforeach
                                    </select>

but I got a wrong result (only classPlayers values in dropdown but not selected)

Any help ? thanks


Solution

  • Your should check $player->id in $players's ids instead in checking players array where that array dosen't contain the ids. So I will pluck the ids of $players from the collection and then convert it into a array $players->pluck('id')->toArray().

    {{ in_array($player->id, $players->pluck('id')->toArray()) ? "selected": ""}}
    

    or you can get model keys (ids) from the controller via

    $playerIds = User::whereRoleIs(['player'])->modelKeys();
    

    #modelKeys()

    Then just check that array in your select option loop.This will save users RAM

     {{ in_array($player->id, $playerIds) ? "selected": ""}}