Adding where clause dynamically to a query with pagination in Laravel

萝らか妹 提交于 2019-12-11 05:57:11

问题


I have a list of items that I want to be able to filter using some buttons in the view (show, which are active, show only ones that start with a certain letter, etc) and I was making a different query for each possible combination and that was getting out of hand as soon as I have more than 3 buttons to filter.

So I want to add a where clause to my initial query depending on the buttons pressed, but what I have so far isn't working and I don't know if it's the pagination:

(This is an example with just one button, I'd add more conditions later but this isn't working already).

public function index()
{
    $hostesses = Hostess::orderBy('lastname', 'asc')
                ->paginate(30);

    if (Input::has('l')){
        $hostesses->where('lastname', 'like', Input::get('l').'%');
    }

    $this->layout->content = View::make('hostesses.index', compact('hostesses'));
}

I get this error on the view:

ErrorException

call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Support\Collection' does not have a method 'where'

回答1:


$hostesses = Hostess::orderBy('lastname', 'asc');

if (Input::has('l')){
    $hostesses->where('lastname', 'like', Input::get('l').'%');
}

$results = $hostessess->paginate(30);

Something like that?



来源:https://stackoverflow.com/questions/23393871/adding-where-clause-dynamically-to-a-query-with-pagination-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!