Laravel: Filtering is eloquent with additional user input

I have a list of news on my laravel site. The /news/ page shows a quick list of stories.

Now I want to allow users to filter the news. For example, show only "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 displays only news in the sports category. This only works if a type is given, and will obviously fail if there is no type specified.

What is the best solution for this? I know that I can check if $input['type'] exists, and if so, write a completely new, second "$news = DB::table('news')..." code, but I think that I really want to have several user inputs, which would make this 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 that I have to miss something obvious here. Can someone point me in the right direction?

+4
source share
1 answer

I think you can do this using a foreach like

 $input = Input::all(); 

So you get something like this (you should check $input not null)

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

Now select a table, for example

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

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

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

Or you can use orderBy as (for multiple dynamic 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(); 

or you can use

 $result = $users->paginate(10); 
+3
source

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


All Articles