0

I was trying to extend my user.blade.php to my views menu.blade.php. Everything works fine with my other views that use the same user.blade.php too. But not with my menu.blade.php, I get an error saying "Undefined variable: categories (View: D:\xampp\htdocs\mieaceh\resources\views\layouts\user.blade.php)" with "Possible typo $categories Did you mean $errors?"

Here are the codes to my user.blade.php

 @foreach($categories as $category)
    <a href="{{ route('menu.index', ['category' => $category->slug]) }}">
       <div class="card-category" style="width: 10rem; height: 4rem;">
          {{ $category->name }}
       </div>
    </a>
 @endforeach

How do I solve it?

  • in the controller you are not passing a variable associate to that key....................... – Alberto Sinigaglia Dec 20 '20 at 14:12
  • If you are using a partial/view in multiple views within the application and the view requires a set of data, then you should use View Composer to avoid fetching the data required by the view at multiple places. Laravel docs: https://laravel.com/docs/8.x/views#view-composers – Donkarnash Dec 20 '20 at 14:20
  • Oh right, thank you @Berto99 –  Dec 20 '20 at 14:23
  • A better alternative to partials and view composers in this case is to use a blade component. Here is the documentation https://laravel.com/docs/8.x/blade#components – Hazem Mohamed Dec 20 '20 at 14:42
  • Does this answer your question? [How to pass data to view in Laravel?](https://stackoverflow.com/questions/18341792/how-to-pass-data-to-view-in-laravel) – miken32 Dec 20 '20 at 16:22

1 Answers1

0

If you want to make a piece of view that appears in multiple places, you can use blade components https://laravel.com/docs/8.x/blade#components.

This will help encapsulating this partials behavior and required data.

Hazem Mohamed
  • 564
  • 3
  • 7