Kryptonit3's avatar

How to filter results based on URL query string

I have a model User and it hasMany Types. I have a page where I paginate all users. I also have a box off to the side with checkboxes with all the types in them. How would I filter the paginated content? I am assuming it has something to do with a query scope but I do not know how to apply it properly, and also without messing up the pagination.

Something like mysite.com/users?type=2,3,5,7&page=2 where type is a comma delimited string of the boxes checked.

0 likes
4 replies
sebdesign's avatar
Level 29

User model

public function scopeType($query, $types) {
    return $query->whereHas('types', function($query) use ($types) {
        return $query->whereIn('id', (array)$types);
    });
}

In your controller:

public function index(Request $request) {
    $types = explode(',', $request->get('type'));

    $users = User::type($types)->paginate();

    return view('users', compact('users'));
}
2 likes
Kryptonit3's avatar

@sebdesign looks good so far. Any easy method for submitting a form and then it redirecting to the url with the get variable in the url?

sebdesign's avatar

What do you mean by the get variable in the url?

When you submit the form with the url in your first question, you should display the results without redirect.

jekinney's avatar

You can submit data via URL, but I think the confusion with your question is you don't need to from a form. The Request gets your post data for you. Consume it in your query and pass it to the view.

Please or to participate in this conversation.