10
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【laravel】repositoryの書き方

Last updated at Posted at 2018-05-14

laravelでのrepositoryの良さげな書き方を紹介します。

class UserRepository implements UserInterface
{
    protected $user;
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    protected function byFilter(array $filter){
        if (array_key_exists('name', $filter)){
            $data->where('name', $filter['name']);
        };
        if (array_key_exists('email', $filter)){
            $data->where('email', $filter['email']);
        };
        if (array_key_exists('point', $filter)){
            $data->where('point', $filter['point']);
        };
        if (array_key_exists('role', $filter)){
            $data->where('role', $filter['role']);
        };
        return $data;
    }

    public function sumPointByFilter(array $filter = [])
    {
        $data = $this->byFilter($filter);
        $data = $data->sum('point');

        return $data;
    }

    public function existsByFilter(array $filter = [])
    {
        $data = $this->byFilter($filter);
        $data = $data->exists();
        return $data;
    }

    public function getByFilter(array $filter = [])
    {
        $data = $this->byFilter($filter);
        $data = $data->get();
        return $data;
    }

}

こうすればgetBy***みたいのを都度書く必要が無くなりRepositoryがスッキリするのではと思いました。

※「もっと良さそうな書き方があるよ」って方は教えてください。

10
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?