我有两个表:用户和问题,我有一个表单来创建问题,还有一个index.blade.php视图来显示所有创建的问题。但是,当我想要显示包含创建的所有问题的索引视图时,会出现此错误:
未定义变量$questions
这是我的UserModel:
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $appends = [
'profile_photo_url',
];
//Relationship onetomany with Questions table
public function questions(){
return $this->hasMany(Question::class);
}这是我的问题模型:
use HasFactory;
protected $fillable = ['question', 'answer', 'user_id'];
//Relationship with User table
public function user(){
return $this->belongsTo(User::class);
}这是发送的索引视图,它位于一个名为admin的文件夹中,这个文件夹是创建的问题的集合
public function index()
{
$questions = Question::all();
return view('admin.index', compact('questions'));
}这是索引中的foreach,用来显示创建的问题,foreach在一个表中:
@foreach($questions as $question)
<tr>
<td>1</td>
<td>{{$question->question}}</td>
<td>{{$question->answer}}</td>
</tr>
@endforeach这是web.php的路线
Route::resource('admin/question', QuestionController::class)->middleware('auth')->names('admin.question');发布于 2022-09-05 20:15:02
回到基础,排除compact引起的问题。如果下列措施有效:
return view('admin.index', ['questions' => Question::all()]);那就需要进一步调查。
empty array
null赋值,是跳过它们吗?
Question::all()返回null,或者
@foreach将处理null value?
d17值?H 218f 219
问你自己,我为什么要使用compact呢?
为什么将数据分配给var并以牺牲性能为代价将其转换为数组项(创建不必要的内存指针会使内存垃圾收集更难,从而对并发用户性能产生负面影响)。
发布于 2022-09-06 01:18:26
尝试删除用户和问题模型中的雄辩关系
https://stackoverflow.com/questions/73614087
复制相似问题