Laravel: dynamic where clause with Elouquent

前端 未结 6 1239
温柔的废话
温柔的废话 2021-02-05 03:44

I am calling URL with search params which are dynamic. How could I form proper Eloquent query?

In theory:

  1. query
  2. query whe
6条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 04:10

    You can pass a callback to the where function.

    So, you can do something like this:

    class TestService {
    
       TestRepository $testeRepository;
    
       public function __construct(TesteRepository $teste) {
          $this->testeRepository = $teste;
       }
    
       public function getAll(array $filters)
       {
          $where = function (Builder $query) use ($filters) {
             collect($filters)
                ->each(function ($value, $param) use ($query) {
                   if ($param === 'test') {
                      $query->where($param, '=', $value); 
                   } else if ($param === 'test2') {
                      $query->orWhere($param, '>', $value);
                   }
                });
          };
          return $this->testRepository->gelAll($where);
       }
    
    class TestRepository
    {
       public function getAll(\Closure $where)
       {
            $query = TestModel::query();
            $query->where($where);
            //and put more stuff here, like:
            //$query->limit(15)->offset(30)
            ...
           return $query->get();
       }
    }
    

    And in your controller you pass the filters:

    class TestControler ...
    {
        public function $index()
        {
           $filters = request()->query();
           return $this->testService->getAll($filters);
        }
    }
    

提交回复
热议问题