laravel 根据mysql表中的数据选择复选框输入

a5g8bdjr  于 2023-05-23  发布在  Mysql
关注(0)|答案(2)|浏览(160)

我有两张table:Videogames包含视频游戏列表,videojuegos_蒂嫩_usuarios包含用户选择的视频游戏。我想要的是显示视频游戏列表,如下面的图片,选择输入显示所有可用的视频游戏和复选框是用户已经选择的视频游戏。此外,用户应该能够编辑视频游戏,选择新的或删除他/她已经选择的游戏。我尝试了下面的代码,但我没有得到任何结果。
先谢了

表:videojuegos_蒂嫩_usuarios

控制器**

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();
}
}

游戏模型

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',
);
}

用户模型

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

我正在显示用户选择的游戏,但我试图做的是显示所有的视频游戏,并显示用户选择的视频游戏所选择的输入。

@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>
cfh9epnr

cfh9epnr1#

// first build an array of the selected video game id's
// this should be in the controller or model depending on your framework

$selected_games = [];
foreach ($user->usersVideogames as $game) {
    $selected_games[] = $game->videogames_id;
}

// then you can loop over all the games and check the 
// ones that are selected by the user
// $videogames equals all the video games you offer

@foreach ($videogames as $game)     
    <div class="form-check form-check-inline">
            <input
            type="checkbox"
            name="videogames[]"
            value="{{ $game->videogames_id }}"
            {{ in_array($game->videogames_id, $selected_games) ? ' checked' : '' }}
            >
            <label for="game-{{ $game->videogames_id }}" 
            class="form-check-label">{{ $game->subtitle }}</label>
        </div>  
@endforeach
7eumitmz

7eumitmz2#

您需要从DB列表中获取所有游戏,然后检查是否包含用户偏好的游戏:

// $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>

相关问题