Laravel数据未传递到下拉框。

huangapple go评论51阅读模式
英文:

Laravel data not passing to Dropdown box

问题

我正在创建 Laravel 中的下拉框,需要从数据库中获取数据填充到下拉框中。我已经实现了这个功能,但遇到了以下问题:

尝试读取字符串上的属性 "id"

我已经尝试了以下方法,但还是遇到了这个问题:

模型 Batch

class Batch extends Model
{
    protected $table = 'batches';
    protected $primaryKey = 'id';
    protected $fillable = ['name', 'course_id', 'start_date'];
    use HasFactory;

    public function course()
    {
        return $this->belongsTo(Course::class);
    }
}

控制器 BatchController

public function create(): View
{
    $courses = Course::pluck('name', 'id');
    return view('batches.create', compact('courses'));
}

批次视图 batch view

<select name="course_id" id="course_id" class="form-control">
@foreach($courses as $item)
    <option value="{{ $item->id }}">{{ $item->name }}</option>
@endforeach
</select>

希望这些信息有助于解决你遇到的问题。

英文:

i am creating the dropdownbox in laravel i need to fetch data from the database to the dropdownbox. i have done it but i ran into the problem with

Attempt to read property &quot;id&quot; on string

what i tried so far i attached below.some one help me to solve this problem please.
Model

Batch

class Batch extends Model
{
    protected $table = &#39;batches&#39;;
    protected $primaryKey = &#39;id&#39;;
    protected $fillable = [&#39;name&#39;, &#39;course_id&#39;, &#39;start_date&#39;];
    use HasFactory;

    public function course()
    {
        return $this-&gt;belongsTo(Course::class);
    }
}

BatchController

public function create(): View
{
    $courses = Course::pluck(&#39;name&#39;,&#39;id&#39;);
    return view(&#39;batches.create&#39;, compact(&#39;courses&#39;));

}

batch view

&lt;select name=&quot;course_id&quot; id=&quot;course_id&quot; class=&quot;form-control&quot;&gt;
 @foreach($courses as $item)
&lt;option value=&quot;{{ $item-&gt;id }}&quot;&gt;{{ $item-&gt;name}}&lt;/option&gt;
 @endforeach

</select>

答案1

得分: 2

因为 $item 是一个字符串(课程的名称)而不是一个对象,所以会引发错误。

要解决这个问题,修改您的 Blade 文件,使其直接使用键(课程 ID)和值(课程名称),如下所示:

<select name="course_id" id="course_id" class="form-control">
    @foreach($courses as $id => $name)
        <option value="{{ $id }}">{{ $name }}</option>
    @endforeach
</select>
英文:

Because $item is a string (the name of the course) rather than an object, it throws an error.

To fix this, modify your blade file so that it uses the key (course id) and value (course name) together directly, like in:

&lt;select name=&quot;course_id&quot; id=&quot;course_id&quot; class=&quot;form-control&quot;&gt;
    @foreach($courses as $id =&gt; $name)
        &lt;option value=&quot;{{ $id }}&quot;&gt;{{ $name }}&lt;/option&gt;
    @endforeach
&lt;/select&gt;

huangapple
  • 本文由 发表于 2023年6月1日 16:48:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76380160.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定