Checkbox inputs selected based on data from mysql table

huangapple go评论93阅读模式
英文:

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

Table: videojuegos_tienen_usuarios

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>
英文:

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

Checkbox inputs selected based on data from mysql table

Table: videojuegos_tienen_usuarios

Checkbox inputs selected based on data from mysql table

CONTROLLER

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

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

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

$data = $request-&gt;except([&#39;_token&#39;]);

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

Videogame Model

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

public function users()
{
return $this-&gt;belongsToMany(
User::class,
&#39;videojuegos_tienen_usuarios&#39;,
&#39;videogames_id&#39;,
&#39;user_id&#39;,
&#39;videogames_id&#39;,
&#39;user_id&#39;,
);
}

User Model

public function usersVideogames()
{
return $this-&gt;belongsToMany(Videogames::class, &#39;usuarios_tienen_videojuegos&#39;, &#39;user_id&#39;, &#39;videogames_id&#39;);
}

public function getGameId(): array
{
return $this-&gt;videogames-&gt;pluck(&#39;videogames_id&#39;)-&gt;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-&gt;usersVideogames as $game)
&lt;div class=&quot;form-check form-check-inline&quot;&gt;
&lt;input
type=&quot;checkbox&quot;
name=&quot;videogames[]&quot;
value=&quot;{{ $game-&gt;videogames_id }}&quot;
@checked($user-&gt;usersVideogames)
&gt;
&lt;label for=&quot;game-{{ $game-&gt;videogames_id }}&quot; class=&quot;form-check-label&quot;&gt;{{ $game-&gt;subtitle }}&lt;/label&gt;
&lt;/div&gt;
@endforeach

&lt;button type=&quot;submit&quot;&gt;Update Games&lt;/button&gt;

答案1

得分: 1

// 首先建立一个选定的视频游戏ID数组
// 这应该根据你的框架放在控制器或模型中

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

// 然后你可以循环遍历所有游戏并检查
// 用户选定的那些游戏
// $videogames 包含你提供的所有视频游戏

@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
英文:
// first build an array of the selected video game id&#39;s
// this should be in the controller or model depending on your framework

$selected_games = [];
foreach ($user-&gt;usersVideogames as $game) {
	$selected_games[] = $game-&gt;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) 	
	&lt;div class=&quot;form-check form-check-inline&quot;&gt;
			&lt;input
			type=&quot;checkbox&quot;
			name=&quot;videogames[]&quot;
			value=&quot;{{ $game-&gt;videogames_id }}&quot;
			{{ in_array($game-&gt;videogames_id, $selected_games) ? &#39; checked&#39; : &#39;&#39; }}
			&gt;
			&lt;label for=&quot;game-{{ $game-&gt;videogames_id }}&quot; 
            class=&quot;form-check-label&quot;&gt;{{ $game-&gt;subtitle }}&lt;/label&gt;
		&lt;/div&gt;	
@endforeach

答案2

得分: 0

你需要从数据库中获取所有游戏的列表,然后检查是否包含用户喜欢的游戏:

// $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">更新游戏</button>
英文:

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)
  &lt;div class=&quot;form-check form-check-inline&quot;&gt;
    &lt;input
    type=&quot;checkbox&quot;
    name=&quot;videogames[]&quot;
    value=&quot;{{ $game-&gt;videogames_id }}&quot;
    @checked($user-&gt;usersVideogames-&gt;contains($game))
    &gt;
    &lt;label for=&quot;game-{{ $game-&gt;videogames_id }}&quot; class=&quot;form-check-label&quot;&gt;{{ $game-&gt;subtitle }}&lt;/label&gt;
  &lt;/div&gt;
@endforeach

&lt;button type=&quot;submit&quot;&gt;Update Games&lt;/button&gt;

huangapple
  • 本文由 发表于 2023年5月22日 05:17:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76301958.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定