Home » Php » Can't get foreach in index page in laravel 5.5

Can't get foreach in index page in laravel 5.5

Posted by: admin October 26, 2017 Leave a comment

Questions:

I can’t get my categories name in indexpage in laravel 5.5,

here is my controller:

public function leftmenu() {
      $categories = Category::orderby('id', 'desc')->take(9)->get();
      return view('frontend.slider', compact('categories'));
    }

my route:

Route::get('/slider', '[email protected]');

my layout:

@include('frontend.slider')

and my blade:

@foreach($categories as $category)
<li class="nav-item _icon">
<a href="./collections-all.html">
<img src="{{asset('default/frontend/assets/images/home3_icon_electronics.png')}}" alt="electronics">
<span>{{$category->title}}</span>
</a>
</li>
@endforeach

Here is the error i get:

Undefined variable: categories (View:
C:\laragon\www\xxxxxxxx\resources\views\frontend\slider.blade.php)
(View:
C:\laragon\www\xxxxxxxx\resources\views\frontend\slider.blade.php)
(View:
C:\laragon\www\xxxxxxxx\resources\views\frontend\slider.blade.php)

Answers:

You have to add a view composer, in the app > Providers > ComposerServiceProvider in the boot method add :

View::composer('frontend.slider', function ($view) {
    $categories = Category::orderby('id', 'desc')->take(9)->get();
    $view->with('categories', $categories);
});

Why ?

Because you include the slider in the layout so if you visit just the home page you will see the slider the problem here is that you call leftmenu when visiting /slider not the home page where the categories not exists.