1
votes

I am implementing a repository pattern in Laravel and have a question about the implementation.

For example, I can make UserRepository class have methods which follow Eloquent standard:

public function create(array $properties)
{
    return $this->entity->create($properties);
}

public function update($id, array $properties)
{
    return $this->find($id)->update($properties);
}

public function delete($id)
{
    return $this->find($id)->delete();
}

And then inject that repository where ever I need to do something with my user.

The problem I see here is...what happens in the back when I do for example:

$this->userRepository->authenticatedUser()->posts

Does this violate having the repository pattern if the posts relation is called through Eloquent then?

Does having a "real" repository pattern mean then to handle all possible relations which are loaded through the User model?

1
You're no longer using the repository, so it's related to what you specify as the return value for authenticatedUser in your interface.Devon
In my opinion, any attempt to use a 'true' repository pattern with an active record implementation like Eloquent would require a lot of duplication of the eloquent model itself. You can already see that from your code. I don't think it's worth the effort reallyTeliov

1 Answers

2
votes

Keep it DRY. Here you would just duplicate a lot of code that Eloquent already provides.

However you could use the RepositoryPattern if the calls are more complicated and you don't want to repeat the logic all over your codebase.

I.e.

public function clientContact($clientId) {
     return \Auth::user()->manager()->superBoss()->company()->clients()->where('client_id', $clientID)->primaryContact()->firstOrFail();
}

In that case it makes sense.

But if you want the authenticated user's posts then just work with eloquent relationships.

$posts = \Auth::user()->posts()->get();