[英]route with parameters for search results laravel
I have a simple event list, which I take from the Events table. 我有一个简单的事件列表,可从“事件”表中获取。 The view where I list the events has a sidebar with four categories. 我列出事件的视图的边栏包含四个类别。 I want, when clicking on a category, to access the route "events?category=2" for example and show only the events in that category. 我想在单击类别时访问例如“ events?category = 2”路由,并仅显示该类别中的事件。
I created a service provider which provides the categories from the database table "categories" for the table, and the link in the sidebar is 我创建了一个服务提供程序,该服务提供程序提供了数据库表“类别”中的表类别,并且侧栏中的链接为
<a href="{{ route('searchByCategory', ['id' => $category->id] ) }}">
The routes are 路线是
Route::get('events', 'EventsController@mainList')->name('events');
Route::get('searchEventByCategory','EventsController@searchEventByCategory')->name('searchByCategory');
And the EventsController is as follows: 而EventsController如下:
public function mainList(Request $request){
$events = Event::all();
return view('pages.events', compact('events'));
}
public function searchEventByCategory(Request $request){
$events = Event::where('category',$request->query('id'));
return redirect()->route('events', compact('events'));
}
This doesn't work, as, on calling the controller in the 'events' route, the $events variable is overridden, even if I pass it as argument to the route. 这是行不通的,因为在“事件”路由中调用控制器时,即使将其作为参数传递给路由,$ events变量也会被覆盖。
I can't think of anything to go around this problem. 我想不出什么办法解决这个问题。 How could I approach it? 我该如何处理?
I forgot to add the get() method when querying the database, so it's 我忘记了在查询数据库时添加get()方法,因此
$events = Event::where('category',$request->query('id'))->get();
You shouldn't redirect, just return the same view: 您不应该重定向,只需返回相同的视图即可:
$events = Event::where('category', $request->id)->get();
return view('pages.events', compact('events'));
Instead of redirecting to events route
, return the view
from your controller. 无需重定向到事件route
,而是从控制器返回view
。
public function mainList(Request $request){
$events = Event::all();
return view('pages.events', compact('events'));
}
public function searchEventByCategory(Request $request){
$events = Event::where('category',$request->query('id'));
return view('pages.events', compact('events'));
}
If you want to use same /events
route for both do these instead : 如果您要对两者使用相同的/events
路由,请改用以下方法:
In your sidebar : 在边栏中:
<a href="{{ route('events', ['id' => $category->id] ) }}">
In your controller : 在您的控制器中:
public function mainList(Request $request){
if($request->has('id')){
$events = Event::where('category',$request->get('id'));
} else {
$events = Event::all();
}
return view('pages.events', compact('events'));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.