Reputation:
I'm trying to share the result from query to all views but it doesn't seems to work.
I have in my Category model this
public function getAllImageCategories()
{
$categoires = Category::all();
return $categoires;
}
Then in my HomeController __constructor this
public function __construct()
{
$Category = new Category;
$allCategories = $Category->getAllImageCategories();
View::share('allCategories', $allCategories);
$this->middleware('auth');
}
And in the view
@foreach($allCategories as $category)
<li><a href="#"><i class="fa fa-btn fa-sign-out"></i>{!! $category->name !!}</a></li>
@endforeach
The error
Undefined variable: allCategories
Why is this error? What I mistaken here?
Upvotes: 1
Views: 65
Reputation: 4315
I suggest you to use the View Composer for all view pages.
https://laravel.com/docs/5.4/views#view-composers
Otherwise you can use Sharing Data With All Views on the same page go to
your/project/directroy/app/Providers/AppServiceProvider.php
and add your code into boot method
public function boot()
{
$Category = new Category;
$allCategories = $Category->getAllImageCategories();
View::share('allCategories', $allCategories);
}
Upvotes: 2
Reputation: 163788
You should put the code into the boot()
method of service provider:
public function boot()
{
$Category = new Category;
$allCategories = $Category->getAllImageCategories();
View::share('allCategories', $allCategories);
}
You should place calls to share within a service provider's
boot
method. You are free to add them to theAppServiceProvider
or generate a separate service provider to house them.
https://laravel.com/docs/5.4/views#sharing-data-with-all-views
Upvotes: 0