How do I make the checkbox 'checked' after saving in the bank?

0

My checkbox are saving normally, however, when I leave the page and return, they are not checked.

Clients.blade.php

<body><formmethod="POST" action="/user/update/client">

        <input type="hidden" name="id" value="{{$user->ID}}" />

        <h1>BEM VINDO ADMINISTRADOR!</h1>

        <div><input type="button" value="Início" id="inicio" name="Início" onclick="window.location.href='/inicioadm';"></div> <br>        
         @foreach ($clients as $client)                                    
        <table style="width:100%">
        <tr>
            <th width="30%"><p>Nome: {{$client->Nome}} <input name="clientes[]" type="checkbox" value="{{$client->ID}}"> </p></th>       
        </tr>
        </table>

        @endforeach

        <br><div><input type="submit" value="Salvar" id="salvar" name="Salvar" onclick="window.location.href='/desenvolvedores"/div>


    </form>
</body>

Controller

public function updateClient()
    {                    
        $clientList = Input::get("clientes");
        $user = Input::get("id");

        \App\Relation::where('ID_user', $user)->delete();

        if($clientList)
        {
            foreach($clientList as $c)
            {
                $r = new \App\Relation();
                $r->ID_clients = $c;
                $r->ID_user = $user;

                $r->save();
            }
        }

        return redirect("/desenvolvedores");
    }

Model Clients

class Clients extends Model
{
    public function Users ()
    {
        return $this->belongsToMany("\App\Relation", "relations", "ID_clients", "ID"); //conectando as tabelas 'users' e 'clients' do banco de dados
    }
}
    
asked by anonymous 30.03.2017 / 14:54

1 answer

2

In a project I used Laravel 5, I also had a similar scenario.

I had a belongsToMany relationship and needed to check in the checkbox what items existed in the relationship.

I used the Collection::contains method. It will check in the collection, without having to do several queries in the database, but only working with the result already loaded.

See an example:

@foreach ($grupos as $grupo)

<div class='checkbox'>
    <label>
        <input type="checkbox" 
              name="grupo_id[]" 
              value="{{ $grupo->id }}" 
             {{ $usuario->grupos->contains($grupo->id) ? 'checked' : '' }}>
        {!! $grupo->nome !!}
    </label>
</div>
@endforeach

Note that in my example, Usuario has relationship BelongsToMany with Grupo .

I've listed all items from Grupo and through the relationship already loaded from Usuario i czech through method contains to know if that id is present in the loaded relationship. If it is, the checkbox will be marked as checked .

    
07.04.2017 / 02:59