我有两个表:用户和问题,我有一个用于创建问题的表单和一个用于显示创建的所有问题的 index.blade.php 视图。但是当我想显示包含创建的所有问题的索引视图时,出现此错误:
未定义变量$问题
这是我的用户模型:
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');
回到基础,排除由
compact
引起的问题。
如果以下方法有效:
return view('admin.index', ['questions' => Question::all()]);
然后需要进一步调查。
compact
如何处理null
作业,它会跳过它们吗?Question::all()
是返回null
还是empty array
?@foreach
如何处理null
值?null
值吗?问问自己,我为什么要使用
?compact
为什么要以性能为代价将数据分配给 var 并将其转换为数组项(创建不必要的内存指针会使内存垃圾收集的寿命变得更加困难,从而对并发用户性能产生负面影响)。
尝试删除用户和问题模型中的雄辩关系
1.在使用循环之前,首先检查数据是否为空或包含数据,2.如果为空,您可以添加三元运算符(例如:如果是集合,则添加$data->isEmpty(),如果是空($data)数组)