DEV Community

Discussion on: Repository Pattern in Laravel

Collapse
 
shokme profile image
Jordan Massart

Hello David,

Thank you for this well presented article :)
I'm not a fan of repository pattern, but I recently do a kind of it by splitting Eloquent and Collection from the model.

I don't know if you are aware of it so I'm sharing it to you:

Models/User.php

public function newEloquentBuilder($query)
{
    return new UserEloquentBuilder($query);
}

public function newCollection(array $models = [])
{
    return new UserCollection($models);
}
Enter fullscreen mode Exit fullscreen mode

UserEloquentBuilder.php

<?php

namespace App\Models\EloquentBuilders;

use Illuminate\Database\Eloquent\Builder;

class UserEloquentBuilder extends Builder
{
    public function member()
    {
        $this->where('type', 'member');

        return $this;
    }
}
Enter fullscreen mode Exit fullscreen mode

UserCollection.php

<?php

namespace App\Models\Collections;

use Illuminate\Database\Eloquent\Collection;

class UserCollection extends Collection
{
    public function active()
    {
        return $this->where('status', 'active');
    }
}

Enter fullscreen mode Exit fullscreen mode
User::member()->get()->active();
Enter fullscreen mode Exit fullscreen mode

I discovered this possibilty by reading this article

Collapse
 
davidrjenni profile image
David

I appreciate your feedback very much!

Thank you for this well presented article :)
I'm not a fan of repository pattern, but I recently do a kind of it by splitting Eloquent and Collection from the model.

I don't know if you are aware of it so I'm sharing it to you:

No, I wasn't aware about this, thanks for sharing the link. It looks neat and I hope to try it out soon.

I certainly see why it might be more popular in the Laravel community. In the end, the design decisions depend a lot on personal taste, the specific project and other factors. But whatever helps you structure your project is great!