Reputation: 145
Hi Im trying to display my data from the database to my views in Laravel 5.3
But Im having this error
Undefined variable: guests (View: C:\Users\NtechB02-Chu\Desktop\laravel_projects\2fplaza\resources\views\admin\guests.blade.php)
This is my declare routes
Route::resource('/guests', 'GuestController');
and my Controller
public function index()
{
$guests = DB::table('users')->where('roles_id', '2')->orderBy('id')->chunk(10, function($guests) {
foreach ($guests as $guest) {
echo $guest->firstname . $guest->lastname;
}
return false;
});
return view('admin.guests', ['users' => $guests]);
}
Lastly my views file
@foreach ($guests as $guest) {{$guest->firstname}}
@endforeach
I hope you could help me guys. Thanks!
Upvotes: 0
Views: 882
Reputation: 2270
you have send users variable how can guest can be fetch in forloop do like this
public function index()
{
$guests = DB::table('users')->where('roles_id', '2')->orderBy('id')->chunk(10, function($guests) {
foreach ($guests as $guest) {
echo $guest->firstname . $guest->lastname;
}
return false;
});
return view('admin.guests',compact('guests'));
}
Upvotes: 0
Reputation: 145
I found a solution!
Instead of doing the query inside my controller I placed in the AppServiceProvider under the folder App/Providers
use View;
use Illuminate\Support\Facades\DB;
public function boot()
{
$guests = DB::table('users')->where('roles_id', '2')->first();
View::share('guest', $guests);
}
I was bale to access it in my views
Upvotes: 1
Reputation: 1358
return view('admin.guests', ['guests' => $guests]); or you can alternatively do.
return view('admin.guests')->('guests', $guests)->render();
Upvotes: 0