I'm using a package with cities and countries in my Laravel project. I set up a repository pattern to use this cities data. My plan is to send the cities data to the register view or any other view I want. In the example here I want to send to the project.create page. I tested the repository and when I look through the controller, I can pass the data to the view and print it with dd(). There is no problem with this. Now I want to send this data to a view i want via viewcomposer.
First of all, I wrote a ComposerServiceProvider.php file as follows
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
View::composer(
'project.create',
'App\View\Composers\LocationComposer'
);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
Then I wrote the composer file, which is as follows:
<?php
namespace App\View\Composers;
use App\Repository\Eloquent\LocationRepository;
use Illuminate\View\View;
class LocationComposer
{
/**
* @var LocationRepository
*/
public $locationlist;
/**
* LocationComposer constructor.
* @param LocationRepository $locations
* @return void
*/
public function __construct(LocationRepository $locations)
{
$this->locationlist = $locations->getAllCities();
}
/**
* Bind data to the view.
*
* @param \Illuminate\View\View $view
* @return void
*/
public function compose(View $view)
{
$view->with('cities', $this->locationlist);
}
}
But the data does not pass to the view I want.
Things I've tried and done: -I registered the composerserviceprovider via app config. -I ran php artisan config:clear -I tried to send to other views Welcome, register etc.
I suspect I am not invoking the repository correctly into composer.
Thanks for your help...
CodePudding user response:
Probabaly you didn't add App\Providers\ComposerServiceProvider::class
into your config/app.php
file. All additional service providers need to be added into providers
array of config/app.php
file.