Laravel checkbox checked or not checked according to Database

Asked

Viewed 2,123 times

4

I need some help on Laravel on how to "check checkboxes" on a form. I have a table colors, today with 12 different colors but can be as many as I want. And a table corproduto. The colors.id = corproduto.cor_id. When I register the product I choose the colors it will have. So far so good. But when I edit this product, I would like to see the list of all colors and the one that are used (checked). I checked this link, https://laracasts.com/discuss/channels/general-discussion/getting-a-checkbox-checked but I couldn’t. The image below is from the registration. I appreciate any help. Valdir

Tela de Cadastramento de Produtos, escolhendo as cores

  • I would make a left join of the table colors for the table of the relation, checked the ones that are null who are the ones who had no record, rode a foreach in the result with that difference

2 answers

0

There is then a relationship Muitos para Muitos (N:M), where the tables Produto and Cores has an intermediate table with its respective keys:

Model Cor:

<?php

namespace App\Models;    
use Illuminate\Database\Eloquent\Model;

class Cor extends Model
{
    protected $table = 'cor';    
    protected $fillable = array('descricao');    
    protected $primaryKey = 'id';    
    public $timestamps = false;  

    //relação muitos para muitos.
    public function produtos()
    {
        return $this->belongsToMany(Produto::class,'produto_cor','cor_id', 'produto_id');
    }
}

Model Produto:

<?php

namespace App\Models;    
use Illuminate\Database\Eloquent\Model;

class Produto extends Model
{
    protected $table = 'produto';    
    protected $fillable = array('description', 'cor_id');    
    protected $primaryKey = 'id';
    public $timestamps = false;

    //relação muitos para muitos.
    public function cores()
    {
        return $this->belongsToMany(Cor::class,'produto_cor','produto_id', 'cor_id');
    }
}

In the Controller

public function index()
{
    $id = 1; // código do produto
    $result = Cor::leftJoin('produto_cor', function($join) use ($id)
        {
            $join->on('produto_cor.cor_id', '=', 'cor.id')
                ->where('produto_cor.produto_id', (int)$id);

        })
        ->select(\DB::raw('cor.id, cor.descricao, if(produto_id is null, 0, 1) corstatus'))
        ->orderBy('cor.descricao')
        ->get();
    return view('test.index', compact('result'));
}

in the variable $result return to color list with an extra field corstatus where corstatus = 1 to color is present in that product, not different.

And finally in View:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel - Test</title>
    {{ Html::script('js/jquery.v1.11.0.js') }}
</head>
<body>
    @foreach($result as $r)     
        <div>
        <input @if((int)$r->corstatus==1) {!! 'checked="checked" ' !!} @endif type="checkbox" name="cor[]" value="{{$r->id}}">{{$r->descricao}}
        </div>
    @endforeach
</body>
</html>
  • Hello Virgil already have an intermediate table "corproduto" that contains a field cor_id (ref. table colors,one for one) because I can not repeat the colors, and a product_id (ref. table products, one for many) the product for various colors. I don’t have the "corstatus" field, because I couldn’t save the false checkbox from View(form). I used Input::get('color') of course it just "picks" the checked, Some additional information I already appreciate. Kaztyx.

  • So, you have a design error in your design, because colors can be in all products and products can have multiple colors, so you really need a many to many table that can be this corproduct(product_id, cor_id) following this idea. Example I can have like this (1,1),(1,2), (1,3), (2,1),(2,2) that is to say have two products ai 1 and 2 with colors 1, 2 and 3. The main idea is this. Then it is mount SQL to bring all the colors of a particular product, as you asked and I made an example.

  • that corstatus is a function I put to satisfy and say which ones are with 1 and 0 where 0 has not been selected.

0


To do this, you first need to have the relationships properly configured in your model.

For example:

class Cor extends Eloquent {

}


class Produto extends Eloquent {
    public function cores() {
       return $this->hasMany(Cor::class, 'cor_id');
    }
}

If you are using the Form::model of Laravel, you need to just do so:

{{ Form::model($produto) }}

 @foreach($cores as $cor)
    {{ Form::checkbox('cores[]', $cor->id) }} {{ $cor->nome }}
 @endforeach

{{ Form::close() }}

By doing this, automatically the colors that are present in the Produto will be checked at checkbox.

If it is complicated to make the form above because of internal nomenclatures, you also have the option to use the method contains, present in the Collection.

Behold:

 @foreach($cores as $cor)
    {{ 
       Form::checkbox(
           'cores[]',
           $cor->id,
           $produto->cores->contains($cor->id)
       ) 
     }}
     {{ $cor->nome }}
 @endforeach

This answer applies if you are using Laravel 4, or Laravel 5 along with the Laravel Collective library. If you’re not using, you’ll have to do the if at hand, in HTML.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.