Reputation: 1101
i have laravel 5.3 project im trying to share with all views .. so i was trying this .. in appserviceproviders this is the boot function
View::share('path', '/final/public/');
ok its working .. but what i want to do is share variable with all views like count model records i mean like this ..
$items = Item::get();
View::share('variable',$items);
but its not shearing anything . so i tried to put it in this class ..
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
private $itemss;
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->itemss = Item::get();
view()->share('itemss', $this->itemss);
});
}
}
and i gat the same error
ErrorException in 4f8648bebb04d05a1427fdfec486dd0221e1b875.php line 235:
Undefined variable: itemss (View:
E:\AppServ\www\final\resources\views\layouts\adminmaster.blade.php) (View:
E:\AppServ\www\final\resources\views\layouts\adminmaster.blade.php)
Upvotes: 0
Views: 50
Reputation: 3266
You may need to extend the scope of variable with use
keyword.
public function __construct()
{
$this->middleware(function ($request, $next) use ($itemss) {
$this->itemss = Item::get();
view()->share('itemss', $this->itemss);
});
}
From docs:
A closure encapsulates its scope, meaning that it has no access to the scope in which it is defined or executed. It is, however, possible to inherit variables from the parent scope (where the closure is defined) into the closure with the use keyword
Upvotes: 1