Home > Back-end >  php Laravel 9 Undefined variable $questions
php Laravel 9 Undefined variable $questions

Time:09-06

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 compact handle a null assignment, does it skip them?
  • Is Question::all() returning null or an empty array?
  • How would @foreach handle a null value?
  • Should I ensure an empty array is presented instead of null value?

Ask your self, why am I using compact at 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

  • Related