I’m using view composer in Laravel as follows:
namespace AppProviders;
use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesView;
use AppModelsGreen;
use AppModelsBlue;
class SidebarServiceProvider extends ServiceProvider
{
public function boot(): void
{
View::composer('layouts.sidebar', function ($view) {
$dataGreen = Green::all();
$dataBlue = Blue::all();
$view->with([
'green' => $dataGreen,
'blue' => $dataBlue
]);
});
}
}
Then I added my provider to the array:
AppProvidersSidebarComposerServiceProvider::class,
But I get the following framework error when I try to return a data with @foreach
Undefined variable $dataGreen
2
Answers
The error message "Undefined variable $dataGreen" indicates that the variable $dataGreen is not recognized within the view where you are using @foreach to iterate over it. To resolve this issue, you need to make sure that the variable is properly passed to the view.
In your SidebarServiceProvider class, you are passing the variables $green and $blue to the view, not $dataGreen and $dataBlue. Therefore, you should update your view composer as follows:
Now, in your view file (layouts.sidebar), you can access the variables green and blue directly:
This is because the variables which are defined are $green and $blue due to being the names you are returning in the view composer, not the the declared variables within the function.