jreikes
jreikes

Reputation: 714

Why won't Laravel pass my variable to blade template?

I'm using Laravel 5.2. In routes.php, I have:

Route::get('test', function() {
    $events = App\Event::get();
    return view('test', $events);
});

In test.blade.php, I have:

<?php print_r($events) ?>

And I get:

ErrorException in ....php line 11: Undefined variable: events (View: .../test.blade.php)

My get() statement is working properly (print_r($events) works in routes.php). Why isn't it getting passed to the blade template?

Upvotes: 1

Views: 390

Answers (2)

Thomas Kim
Thomas Kim

Reputation: 15961

You are not passing the data correctly. Try this instead:

return view('test', ['events' => $events]);

You have other options too. For example:

return view('test', compact('events'));

return view('test')->with(['events' => $events]);

Source: https://laravel.com/docs/5.2/views

Upvotes: 3

Bojan Kogoj
Bojan Kogoj

Reputation: 5649

return view('test', ['events' => $events]);

you can also display value like this in blade (for testing)

{{ dd($events) }}

Upvotes: 1

Related Questions