英文:
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 "id" 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 = '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>
答案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:
<select name="course_id" id="course_id" class="form-control">
@foreach($courses as $id => $name)
<option value="{{ $id }}">{{ $name }}</option>
@endforeach
</select>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论