lundi 9 décembre 2019

Laravel Dynamic Checkbox error: Trying to get property 'id' of non-object

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



Aucun commentaire:

Enregistrer un commentaire