G
G
ganjo8882019-04-04 18:15:23
Laravel
ganjo888, 2019-04-04 18:15:23

How to write a query correctly in Laravel?

Displays an error that there are not enough arguments in an anonymous function, help to implement the intended request

foreach ($filters as $filter) {
            if ($filter['operation'] === 'in') {
                $builder = $builder->whereHas('resource', function ($query, $filter) {
                    $query->whereIn($filter['name'], $filter['value']);
                });
            } else {
                $builder = $builder->whereHas('resource', function ($query, $filter) {
                    $query->where($filter['name'], $filter['value']);
                });
            }
        }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
netrox, 2019-04-04
@ganjo888

foreach ($filters as $filter) {
  
            if ($filter['operation'] === 'in') {
                $builder = $builder->whereHas('resource', function ($query) use ($filter) {
                    $query->whereIn($filter['name'], $filter['value']);
                });
            } else {
                $builder = $builder->whereHas('resource', function ($query) use ($filter) {
                    $query->where($filter['name'], $filter['value']);
                });
            }
        }

H
hOtRush, 2019-04-04
@hOtRush

$builder = $builder->whereHas('resource', function ($query) use ($filter) {
    $method = $filter['operation'] === 'in' ? 'whereIn' : 'where';
    $query->$method($filter['name'], $filter['value']);
});

N
NubasLol, 2019-04-04
@NubasLol

What are 2 identical requests for? Use the function below which will wrap the value in an array if it is not an array

$builder = $builder->whereHas('resource', function ($query, $filter) {
                    $query->whereIn($filter['name'],  array_wrap($filter['value']));
                });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question