S
S
SpinPr2018-05-10 15:40:10
Laravel
SpinPr, 2018-05-10 15:40:10

How to implement a complex filter on the selection of goods from the database in Laravel?

While doing this:
Count the number of products that satisfy the filter:
$kol = \App\Good::select('id', 'name')->where(function ($query) {
if (...) {
$query-> where('id','>',0);
}
...
many conditions
...
})->count();
Get the product page by filter:
$sel = \App\Good::select('id', 'name')->where(function ($query) {
if (...) {
$query->where('id ','>',0);
}
...
many conditions
...
})->skip(($pg-1)*$max)->take($max)->get();
Is it possible to make a condition for the filter 1 time and then substitute it in the selection?
How to implement it?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
J
JimmDiGreez, 2018-05-10
@SpinPr

For example, you can take a function into a variable.

$filter = function(query) {
    // ...
};

Good::select('id', 'name')->where($filter)->count();

S
Sergey Gerasimov, 2018-05-10
@mrTeo

Use scope:

public function scopeFilter($query) 
{
    if (...) {
        $query->where('id','>',0);
    }
    ...
    много условий
    ...
    })->skip(($pg-1)*$max)->take($max)
    return $query;
}

https://laravel.com/docs/5.6/eloquent#local-scopes

V
Vlad, 2018-05-10
@Result007

Can you do it like this

$good_query = Good::query();

if (...) {
    $good_query->where('id', '>', 0);
}

$result = $good_query->skip(($pg-1)*$max)->take($max)->get();

V
vism, 2018-05-10
@vism

$kolQuery = \App\Good::select('id', 'name')->where(function ($query) {
if (...) {
$query->where('id','>', 0);
}
...
many conditions
...
});
$kol = $kolQuery->count();
$sel = $kolQuery->skip(($pg-1)*$max)->take($max)->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question