Reputation: 652
On my website, users can display posts created by other users. However, I have 2 select boxes, one for ordering by name or date and the other is ordering by category. The way I have done it is incorrect and I am aware of that. The simple reason for this is that I don't know how to make an if check on which form submitted the request.
Here is my controller method for displaying the events:
public function getEvents(Request $request){
if($request['sort'] == "created_at"){
$posts = Post::orderBy('created_at', 'desc')->get();
}
elseif($request['sort'] == "title"){
$posts = Post::orderBy('title', 'desc')->get();
}
elseif($request['category'] == "sport"){
$post = Post::where('type', '=', 'sport' )->get();
}
elseif($request['category'] == "culture"){
$post = Post::where('type', '=', 'culture' )->get();
}
elseif($request['category'] == "other"){
$post = Post::where('type', '=', 'other' )->get();
}
else{
$posts = Post::orderBy('created_at', 'desc')->get();
}
return view ('eventspage', ['posts' => $posts]);
}
This is currently incorrect, I want it to follow this structure:
if(request submitted by 'sort')
then do this...
elseif(request submitted by 'category')
then do this...
Here is my view containing the 2 select boxes:
<div class="row">
<div class="col-md-6">
<form action="{{ route('events') }}">
<select name="category" onchange="this.form.submit()" class="form-control">
<option value="sport">sport</option>
<option value="culture">Culture</option>
<option value="other">Other</option>
</select>
</form>
</div>
<div class="col-md-6">
<form action="{{ route('events') }}">
<select name="sort" onchange="this.form.submit()" class="form-control">
<option value="created_at">Date</option>
<option value="title">Title</option>
</select>
</form>
</div>
</div>
Upvotes: 0
Views: 2039
Reputation: 14982
You can have a hidden input in your form with name as formName
and the respective values.
Then it's easy to check which form submitted.
//Category form
<input type="hidden" name="formName" value="category">
//Sort form
<input type="hidden" name="formName" value="sort">
Then, in the controller:
if($request['formName'] == 'category') //request submitted by 'category'
//then do this...
elseif($request['formName'] == 'sort') //request submitted by 'sort'
//then do this...
Just be careful not to put too much different code in both conditionals. If you find yourself having two entirely different functions, create an action for each form.
Upvotes: 1