Reputation: 11
MenusController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Menu;
public function index(){
$menus = Menu::orderBy('created_at' , 'asc')->get();
return view('menus.index')->with('menus' , $menus);
}
views/menus/index.blade.php
@if(count($menus) > 0)
@foreach($menus as $menu)
<h4>{{$menu->category}}</h4>
@endforeach
@else
<p>No menu categories</p>
@endif
So I have a table in my database called “menus” and one of the columns is called “category”.
When I have an entry or entries in that table, my index page loads up normally with the entries from my database also showing up as expected. But if there is nothing on my menus table I will just get a “Undefined variable: menu...” error, but I expect it to just put out “No menu categories”.
Upvotes: 1
Views: 98
Reputation: 4145
Try the following:
@if(isset($menus) && count($menus))
@foreach($menus as $menu)
<h4>{{$menu->category}}</h4>
@endforeach
@else
<p>No menu categories</p>
@endif
Upvotes: 1