user9277271
user9277271

Reputation:

Laravel 8: Undefined variable: questions

I'm working with Laravel 8 to develop to my project.

Now I want to show some data from the DB, so I coded this in the Controller:

use App\Models\Question;
public function index()
{
    questions = Question::all();
    return view('home', compact('questions'));
}

Then at the view home.blade.php, I added this:

@foreach($questions as $question)
<tr>
    <td style="text-align:right;">
        <h3 class="h5 mb-0"><a href="#0" class="text-uppercase">{{ $question->title }}</a></h3>
    </td>
</tr>
@endforeach

But now I get this as error:

ErrorException Undefined variable: questions (View: home.blade.php)

So what's going wrong here ? How can I fix this issue?

I would really appreciate if you share your idea and suggestion about this...

And here is also web.php route, if you want to take a look at:

Route::get('/home', [HomeController::class, 'index'])->name('home');

Thanks in advance.

Upvotes: 0

Views: 691

Answers (3)

Sajid Bashir
Sajid Bashir

Reputation: 36

this is your logic code

$questions = Question::all();

return view('home', compact('questions'));

and view code also be like this that it handle exception

  @if(isset($questions))
    @foreach($questions as $question)
    <tr>
        <td style="text-align:right;">
            <h3 class="h5 mb-0"><a href="#0" class="text-uppercase">{{ $question->title }}</a></h3>
        </td>
    </tr>
    @endforeach
@endif

Upvotes: 0

Switi
Switi

Reputation: 394

you can not include $ in your variable please add

$questions = Question::all();

return view('home', compact('questions'));

Another option you can use

return view('home')->with('questions', $questions);

Upvotes: 0

Ahmed Ali
Ahmed Ali

Reputation: 133

    $questions = Question::all();
return view('home', compact('questions'));

You Forgot the $ before the var name.

Upvotes: 2

Related Questions