4

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?

4

1 回答 1

3

我认为你可以使用foreach循环来做到这一点,例如

$input = Input::all();

所以,你会得到这样的东西(你应该检查$input不为空)

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

现在,选择表格

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

现在喜欢(用于多个动态loop子句)$inputwhere

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

或者您可以使用orderBylike(用于多个动态orderBy子句)

$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();

或者你可以使用

$result = $users->paginate(10);
于 2013-07-28T00:45:42.430 回答