【问题标题】:Laravel Dynamic Checkbox error: Trying to get property 'id' of non-objectLaravel 动态复选框错误:尝试获取非对象的属性“id”
【发布时间】:2020-04-02 17:00:08
【问题描述】:

我想要实现的目标: 用户可以将多个超市分配给一个产品,超市可以分配给多个产品。注册产品时,我希望用户能够从数据库中填充的复选框中进行选择。

产品.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

【问题讨论】:

  • $supermarkets 是一个关联数组,以 'id' 为键,值为 'name';它不包含对象......它是一个字符串数组
  • @lagbox 那么在创建 Product 对象时我将如何保存该复选框的 id 呢?

标签: laravel checkbox laravelcollective


【解决方案1】:

解释一下 cmets 中所说的内容:

您没有在$supermarkets 数据中提供对象,因为您使用的是pluck('name','id')。您正在提供一个关联数组:

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

因此您需要将显示代码更改为:

@foreach ($supermarkets as $id => $name)
    <div class="col-sm-3">
        {!! Form::checkbox('supermarket_id[]', $id) !!}
        {!! Form::label('supermarkets', $name) !!}
    </div>
@endforeach

【讨论】:

  • 非常感谢!我现在明白你必须循环遍历每个键/值作为 $id => $name 才能提取数组中每条记录的值。
猜你喜欢
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
  • 2021-07-30
  • 1970-01-01
  • 2021-05-26
相关资源
最近更新 更多