spatie / laravel-view-models

View models in Laravel
https://spatie.be/open-source
MIT License
1.02k stars 61 forks source link

How can I use this package with Collection of a Model ? #20

Closed rabin-io closed 5 years ago

rabin-io commented 5 years ago

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

    public function index()
    {
        $users = Users::all();

        return view('users.index', compact('users')); // <- can't use with ModelView as it expecting A User Model.
    }

Should I create a method which get the collection and convert each item to the view model object and pass that to the view ?

brendt commented 5 years ago

No, you'd pass the collection to the viewmodel

rabin-io commented 5 years ago

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);
        }
brendt commented 5 years ago

You should change the viewmodel constructor:

    public function __construct(Collection $registrars)
    {
    }
rabin-io commented 5 years ago

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 ?

brendt commented 5 years ago

I'd make two viewmodels.

rabin-io commented 5 years ago

OK, thank you