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.
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:
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.
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
$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.
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 :
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'));
}
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.