Laravel Repositories and Eloquent Models Laravel Repositories and Eloquent Models laravel laravel

Laravel Repositories and Eloquent Models


Repositories in Laravel help keep controllers thin and dumb.

Controllers get to handle any route or data parsing before handing to the repository, and returning data in proper formats.

Repositories get to handle the models.

If you have both of these functions are in the same controller method, you have trouble determining if the issue is in the parsing of the data from the input, or the requesting of data from the model.

This separation allows use to make sure the controller is handing appropriate data to the repository. That the repository is performing the appropriate validations and accessing the model in the correct manner, and that all of these are returning data of the correct type.

The repositories returned model can be tested for type using instanceof:

public function testAllReturnsCollection(){    $collection = $this->machineRepository->all();    $this->assertTrue($collection instanceof \Illuminate\Database\Eloquent\Collection);}public function testFindReturnsMachine(){    $model = $this->machineRepository->find($this->machineId);    $this->assertTrue($model instanceof Machine);}

This type of testing can also be done with Mocking, but when working with models I prefer to use a test database.