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');