Search code examples
phplaraveldatatable

Checkbox inputs selected based on data from mysql table


I’m working with two tables: Videogames with the videogames list and videojuegos_tienen_usuarios with the videogames selected by the users. What I want is to display the videogames list like in the Image below, the select inputs show all the videogames available and the checked boxes are the videogames that the user already selected. Also, the user should be able to edit the videogames selecting new ones or removing the games he/she already selected. I tried with the code below but I'm not getting any result.

thanks in advance

enter image description here

Table: videojuegos_tienen_usuarios

enter image description here

CONTROLLER

public function editGamesUser(int $id)
{
$user = Usuario::findOrFail($id);

return view('admin.videojuegos.usuarios', [
user => $user,
]);
}
public function editExecuteGamesUsers(Request $request, int $id)
{
$request->validate(User::VALIDATE_RULES, User::VALIDATE_MESSAGES);

$user = User::findOrFail($id);

$data = $request->except(['_token']);

try {
DB::transaction(function() use ($user, $data) {
$user->update($data);
$user->usersVideogames()->sync($data['videojuegos_tienen_usuarios'] ?? []);
});
return redirect()
->route('admin.videojuegos.users)
->with('statusType', 'success')
->with('statusMessage', 'The videogames were updated.');
} catch(\Exception $e) {
return redirect()
->route('admin.videojuegos.usuarios', ['id' => $id])
->with('statusType', 'danger')
->with('statusMessage', 'Error.')
->withInput();
}
}

Videogame Model

protected $table = 'videogames';
protected $primaryKey = 'videogames_id';
protected $fillable = ['plataforma_id', 'titulo', 'subtitulo', 'precio', 'fecha_estreno', 'sinopsis', 'contenido' , 'portada', 'portada_juego', 'portada_descripcion', 'categoria_id', 'numjugadores_id', 'img_descripcion'];

public function users()
{
return $this->belongsToMany(
User::class,
'videojuegos_tienen_usuarios',
'videogames_id',
'user_id',
'videogames_id',
'user_id',
);
}

User Model

public function usersVideogames()
{
return $this->belongsToMany(Videogames::class, 'usuarios_tienen_videojuegos', 'user_id', 'videogames_id');
}

public function getGameId(): array
{
return $this->videogames->pluck('videogames_id')->toArray();
}

HTML

I’m displaying the games selected by the user, but what I’m trying to do is to display all the videogames and show the selected inputs with the videogames selected by the user.

@foreach($user->usersVideogames as $game)
<div class="form-check form-check-inline">
<input
type="checkbox"
name="videogames[]"
value="{{ $game->videogames_id }}"
@checked($user->usersVideogames)
>
<label for="game-{{ $game->videogames_id }}" class="form-check-label">{{ $game->subtitle }}</label>
</div>
@endforeach

<button type="submit">Update Games</button>

Solution

  • You need to get from DB list of all games and then check is it contains games prefered by user:

    // $games - collection of all games
    @foreach($games as $game)
      <div class="form-check form-check-inline">
        <input
        type="checkbox"
        name="videogames[]"
        value="{{ $game->videogames_id }}"
        @checked($user->usersVideogames->contains($game))
        >
        <label for="game-{{ $game->videogames_id }}" class="form-check-label">{{ $game->subtitle }}</label>
      </div>
    @endforeach
    
    <button type="submit">Update Games</button>