简体   繁体   中英

Laravel: Filtering in eloquent with optional user input

I have a list of news stories in my laravel website. On the /news/ page a quick list of stories is shown.

Now I want to allow users to filter news. For example, only show "sports" stories.

In my controller I did this:

$input = Input::all();

$events = DB::table('news')
        ->where('category', '=', $input['type'])
        ->order_by('created_at', 'desc')
        ->paginate(10);

Now, this allows me to visit /news?type=sports and it correctly only shows news items within the sports category. This only works if a type is given though, and will obviously fail if there is no type given.

What is the best solution to this? I know I can check to see if $input['type'] exists, and if it does, write a completely new, second "$news = DB::table('news')..." code, but I am thinking that I may actually want to have multiple user inputs, which would make that option not work. For example, what if I want to sort by type and location? Something like /news?type=sports&area=chicago -- what would I do then?

I know I must be missing something obvious here. Can anyone point me in the right direction?

I think you can do it using a foreach loop, for example

$input = Input::all();

So, you'll get something like this (you should check $input is not null)

Array
(
    [type] => sports
    [area] => chicago
)

Now, select the table like

$events = DB::table('news');

Now loop the $input like (for multiple dynamic where clause)

foreach ($input as $key => $value) {
    $events->where($key, $value);
}
$result = $users->get();

Or you can use orderBy like (for multiple dynamic orderBy clause)

$events = DB::table('news')->where('category', $input['type']);
foreach ($input as $key => $value) {
    $events->orderBy($key); // also, you can use ASC/DESC as second argument 
}
$result = $users->get();

or you can use

$result = $users->paginate(10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM