-1

What I'm trying to achieve: User can assign multiple supermarkets to a product, and supermarkets can be assigned to multiple products. When registering a product, I want the user to be able to select from check boxes which are populated from a database.

Product.php

class Product extends Model
{
    //
    protected $fillable = [
        'name',
        'summary',
        'category_id',
        'author_id',
        'supermarket_id',
        'gf_rank_id',
        'average_price',
        'photo_id',
        'online_store_path',
        'ingredients',
    ];

    public function supermarket() {
        return $this->belongsToMany('App\Supermarket');
    }

}

Supermarket.php

class Supermarket extends Model
{
    protected $fillable = [
        'name',
        'url',
    ];

    public function products() {
        return $this->belongsToMany('App\Products');
    }
}

ProductsController.php

  public function create()
    {
        $categories = Category::pluck('name', 'id')->all();
        $supermarkets = Supermarket::pluck('name', 'id')->all();
        return view('admin.products.create', compact(['categories', 'supermarkets']));
    }

create.blade.php

        @foreach ($supermarkets as $supermarket)
        <div class="col-sm-3">
            {!! Form::checkbox('supermarket_id[]', $supermarket->id) !!}
            {!! Form::label('supermarkets', $supermarket) !!}
        </div>
        @endforeach
MattyO
  • 115
  • 2
  • 9
  • 1
    `$supermarkets` is an associative array keyed by 'id' with values being the 'name'; it does not contain objects ... its an array of strings – lagbox Dec 09 '19 at 15:00
  • @lagbox So how would I go about saving the id of that checkbox when create a Product object? – MattyO Dec 09 '19 at 15:12

1 Answers1

0

To explain what has been said in the comments:

You are not supplying an object in your $supermarkets data because you are using pluck('name','id'). You are supplying an associative array:

[ 
    1 => 'supermarket A',
    2 => 'supermarket B'
]

So you need to change your display code to:

@foreach ($supermarkets as $id => $name)
    <div class="col-sm-3">
        {!! Form::checkbox('supermarket_id[]', $id) !!}
        {!! Form::label('supermarkets', $name) !!}
    </div>
@endforeach
RonnyKnoxville
  • 6,166
  • 10
  • 46
  • 75
  • 1
    Thank you so much! I now understand you have to cycle through each key/value as $id => $name to be able to pull the values for each record in the array. – MattyO Dec 10 '19 at 13:38