Closed rabin-io closed 5 years ago
No, you'd pass the collection to the viewmodel
Sorry for the noob question, but I get this error when I pass the Collection directly to the ViewModel
Argument 1 passed to App\ViewModels\RegistrarViewModel::__construct() must be an instance of App\Registrar or null, instance of Illuminate\Database\Eloquent\Collection given
# MyController
public function index()
{
$registrars = new RegistrarViewModel(Registrar::all());
return view('registrars.index', compact('registrars'));
}
# My ViewModel
public function __construct(Registrar $registrar = null)
{
$this->registrar = $registrar ?? new Registrar();
}
So should I just expand the constructor to deal with Collection as well ? somthing like this:
foreach ($registrars as $key => &$registrar) {
$registrars[$key] = new RegistrarViewModel($registrar);
}
You should change the viewmodel constructor:
public function __construct(Collection $registrars)
{
}
Sorry for bugging ,
But if like to handle both cases (Single and Collection) in the same ViewModel
I should refactor the __construct
to handle both cases ?,
and in the case of Collection just loop over the object and convert them one by one ?
I'd make two viewmodels.
OK, thank you
In my index method of the Controller I fetch all users and I like to pass them to the view to allow for replacing some status code with text strings
Should I create a method which get the collection and convert each item to the view model object and pass that to the view ?