Build a query with a conditional where clause in an eloquent model

I need to build a query with an eloquent model, including a conditional where clause. I created something by doing a google search. But it doesn't seem to work.

if ($status) {
    $this->where('status', $status);
}
if ($assignedto) {
    $this->where('assigned_to', $assignedto);
}
if ($fromDate != null && $toDate != null) {
    $this->whereBetween('date', array($fromDate, $toDate));
}
$quotes = $this->orderBy('date', 'desc')->paginate(40);

This returns all results without filtering the status assigned and date.

+4
source share
2 answers

I just updated it by assigning a $thisnew variable, because when I assigned the request to $this, it showed an error, $thisit could not be written on top.

$quoteModel = $this;
if ($status) {
    $quoteModel = $quoteModel->where('status', $status);
}
if ($assignedto) {
    $quoteModel = $quoteModel->where('assigned_to', $assignedto);
}
if ($fromDate != null && $toDate != null) {
    $quoteModel = $quoteModel->whereBetween('date', array($fromDate, $toDate));
}
$quotes = $quoteModel->orderBy('date', 'desc')->paginate(40);

which works great now. But if someone has a better option, please suggest. Thank.

+2
source

. , , .

:

URL Input::get, .

public function scopeFilter($query)
{
    $published = Input::get('published');
    if (isset($published)) $query->where('published', '=', $published);

    return $query;
}

:

filter(), .

public function index()
{
    return View::make('articles.index', [
        'articles' => Article::with('writer')->filter()->get()
    ]);
}
0

Source: https://habr.com/ru/post/1543011/


All Articles