Laravel 8: Undefined variable when loading a Blade into another Blade

Viewed 460

THE SITUATION: I'm making a side Menu that is populated by getting data from a table (MySQL). Every <li> represents one item for the menu:

<li>item 1</li>
<li>item 2</li>
<li>item 3</li>

etc...

THE PROBLEM: All works fine when I see its blade, but when I include it in the main blade, it throws the variable $all_items that contains the data to make the <li> is not recognized (Error: "variable not found error")

THE CODE:

web.php

Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('items', 'MenuCmpItemsController@show');

MenuCmpItemsController.php

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\MenuCmpItems;
use DB;

class MenuCmpItemsController extends Controller
{
    public function show(){
        $all_items = DB::table('tbClassrooms')->select("room_number")->get();
        return view('items', ['all_items'=>$all_items]);
    }
}

items.blade.php (works fine when visiting the URL '/items')

@foreach ($all_items as $item)
<li>{{ $item->cmp_name }}</li>
@endforeach

Now I want to include items.blade.php in auth.blade.php which is the one that contains the following side menu structure:

<div class="collapse show" id="sidemenu">
  <ul class="nav">         
      @include('items')
  </ul>
</div>

But it throws

$all_items is undefined

WHAT I TRIED:

  1. I checked if it could be something else, for example, I replaced "$all_items" with a text, and it loads the text in auth.blade.php, so it seems like the problem is the variable $all_items

  2. I checked if

return view('items')->compact('all_items');

would make any difference but no.

Any suggestions or ideas are highly appreciated.

2 Answers

What is your folder structure? in the resources folder

Solution suggested by shaedrich should resolve your issue.

@include('items', ['all_items'=>$all_items])
Related