I have two tables: Users and Question and I have a form to create questions and an index.blade.php view to show all the questions created. But I have this error, when I want to show the index view with all the questions created:
Undefined variable $questions
This is my 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);
}
This is my Question Model:
use HasFactory;
protected $fillable = ['question', 'answer', 'user_id'];
//Relationship with User table
public function user(){
return $this->belongsTo(User::class);
}
This is my Controller to send the index view which is in a folder called admin, the collection of created questions
public function index()
{
$questions = Question::all();
return view('admin.index', compact('questions'));
}
And this is the foreach in the index to show the questions created, the foreach is inside of a table:
@foreach($questions as $question)
<tr>
<td>1</td>
<td>{{$question->question}}</td>
<td>{{$question->answer}}</td>
</tr>
@endforeach
And this is the route in web.php
Route::resource('admin/question', QuestionController::class)->middleware('auth')->names('admin.question');
CodePudding user response:
Go back to basics, rule out the issue being caused by compact.
If the following works:
return view('admin.index', ['questions' => Question::all()]);
Then further investigation required.
- How would
compacthandle anullassignment, does it skip them? - Is
Question::all()returningnullor anempty array? - How would
@foreachhandle anullvalue? - Should I ensure an empty array is presented instead of
nullvalue?
Ask your self, why am I using
compactat all?Why assign data to a var and cast it to an array item at the cost of performance (creating unnecessary memory pointers makes life for memory garbage collection harder negatively effecting concurrent user performance).
CodePudding user response:
Try Removing the eloquent relationship that's in the User and Question models
