Laravel: Check on which form submitted the request - php

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>

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.

Related

search with pagination is not working in laravel

I make it in 1 route with
in route
Route::get('/all-students', 'AdminController#studentList')->name('admin.student');
Route::post('/all-students', 'AdminController#searchByClassRoll')->name('search-by-class-roll');
in controller funtion student list
public function studentList(Request $request)
{
Session::put('url.intended2', URL::current());
Session::put('url.intended', URL::previous());
if (isset($request->class)) {
if (isset($request->roll)) {
if ($request->class == 'all') {
$students = DB::table('students')
->where('roll', '=', $request->roll)
->orderBy('id', 'DESC')
->paginate(20);
} else {
$students = DB::table('students')
->where('roll', '=', $request->roll)
->where('class', '=', $request->class)
->orderBy('id', 'DESC')
->paginate(20);
}
} else {
if ($request->class == 'all') {
return redirect()->route('admin.student');
} else {
$students = DB::table('students')
->where('class', '=', $request->class)
->orderBy('id', 'DESC')
->paginate(20);
}
}
} else {
$students = DB::table('students')
->orderBy('id', 'DESC')
->paginate(20);
}
return view('admin.student-list')->with('students', $students);
}
post method
public function searchByClassRoll(Request $request)
{
$class = $request->class;
$roll = $request->roll;
if (isset($request->class)) {
if (isset($request->roll)) {
return redirect()->route('admin.student', ['class' => $class, 'roll' => $roll]);
} else {
return redirect()->route('admin.student', ['class' => $class]);
}
}
}
in blade
#if(method_exists($students,'links'))
{!! $students->links() !!}
#endif
normally when I click page 2 it returns
all-students?page=2
when I search something all-students?class=2 and then i click on pagination page it returns again all-students?page=2 and remove the search data from URL.
form from view
<form action="{{ route('search-by-class-roll') }}" method="post">
{{ csrf_field() }}
<input type="hidden" name="type" value="student_list">
<div class="row gutters-8">
<div class="col-4-xxxl col-xl-4 col-lg-3 col-12 form-group">
<div class="ui-alart-box">
<div class="default-alart">
<div class="result" role="alert">
#if(app('request')->input('class') || app('request')->input('roll'))
See All<span> | </span>
#endif
Showing results {{$students->count()}} of {{$students->total()}} entries
</div>
</div>
</div>
</div>
<div class="col-3-xxxl col-xl-3 col-lg-3 col-12 form-group">
<input type="number" name="roll" placeholder="Search by Roll..." class="form-control">
</div>
<div class="col-4-xxxl col-xl-3 col-lg-3 col-12 form-group">
<select class="select2 form-control" name="class" required>
<option value="all">All Classes</option>
<option value="baby">baby</option>
<option value="nursery">nursery</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
<option value="6">six</option>
<option value="7">seven</option>
<option value="8">eight</option>
<option value="9">nine</option>
<option value="10">ten</option>
</select>
</div>
<div class="col-1-xxxl col-xl-2 col-lg-3 col-12 form-group">
<button type="submit" class="fw-btn-fill btn-gradient-yellow">SEARCH</button>
</div>
</div>
</form>
i want to made this because I want this in 1 URL just because if someone manually entered the URL with search data he can see the output. but in here I can't get the result with pagination from blade. when I turned into page 2 it remove the search variable from URL. and paginate the whole data. how can I get result with pagination after search?
There is the simpler way
Just add with your paginated array.
{{ $users->withQueryString()->links() }}
Coming directly to your controller. You don't need any other route or method you can handle this filtering on same route and in same method.
public function studentList(Request $request)
{
if(!empty($request)){
$query = $request->all();
$students = DB::table('students')->orderBy('id', 'DESC');
if(isset($request->class) AND $request->class != '' AND $request->class != 'all')
$students = $students->where('class', '=', $request->class);
if(isset($request->roll) AND $request->roll != '')
$students = $students->where('roll', '=', $request->roll);
$students = $students->paginate(20);
return view('admin.student-list', compact('students','query'));
}
$students = DB::table('students')
->orderBy('id', 'DESC')
->paginate(20);
return view('admin.student-list', compact('students'));
}
Change few things in your view
<form action="{{ route('admin.student') }}" method="get"> change route and method to get
{{ csrf_field() }} //remove this
Below your table inside view write this code. The appends() is most important otherwise pagination in your filtered data won't work.
#if(isset($query))
{{ $students->appends($query)->links() }}
#else
{{ $students->links() }}
#endif
Try use append on paginator blade
{{$students->appends(\Illuminate\Support\Facades\Input::except('page'))->links()}}

How to select an option from the view and search in the controller? (LARAVEL) [duplicate]

This question already exists:
how to implement a search with many filters that the user chooses in Laravel? [closed]
Closed 2 years ago.
I have a code on my blade template page with a search field and a select with options.
The user types what he wants to search in the search field and selects a search option, which must be sent to the controller to search and return the searched customers according to the selected search option.
The view part is ready, but I am still unable to find a way for the controller to choose this option and do the research accordingly.
My client view page:
<form action="{{ route('search') }}" method="POST" class="form form-inline" role="search">
#csrf
<label class="procurar">Procurar for:</label>
<div class="col-3">
<input type="text" name="nome" class="form-control" placeholder="">
</div>
<label>Filtro: </label>
<div class="form-group">
<select name="busca" class="form-control">
<option value="nome">Nome</option>
<option value="tipo_pessoa">Tipo de Pessoa</option>
<option value="cidade">Cidade</option>
<option value="uf">Estado</option>
<option value="cpf_cnpj">CPF /CNPJ</option>
<option value="tipo_cliente">Tipo de Cliente</option>
<option value="onde_nos_encontrou">Onde nos encontrou</option>
</select>
</div>
</form>
My search function:
public function search(Request $request)
{
if ($request->nome)
{
$nome = $request->nome;
$clients = Client::where('nome', 'like', '%'.$nome.'%')
->orderBy('nome')
->paginate(8);
return view('clients.index')
->with('clients', $clients);
}
if ($request->uf)
{
$uf = $request->uf;
$clients = Client::where('uf', 'like', '%'.$uf.'%')
->orderBy('uf')
->paginate(8);
return view('clients.index')
->with('clients', $clients);
}
return redirect()->route('clients.index');
}
Thanks for help!
You need to get the value of busca as that's a select's name. The selected value will be there.
public function search(Request $request)
{
$busca = $request->input('busca', 'nome');
$clients = Client::where($busca, 'like', '%' . $busca . '%')
->orderBy($busca)
->paginate(8);
return view('clients.index')
->with('clients', $clients);
}

Make a blade layout only appear when the users selects from a dropdown using PHP Laravel

Note : I am using Laravel
This is my dropdown and what I want to be able to update my php variable which is stored in my database $SetNewMatch = Auth::user()->dailyMatch;
<form>
<select name = "dailyMatch">
<option value="Pop">Pop</option>
<option value="Classical">Classical</option>
<option value="Rock">Rock</option>
</select>
<button type="submit">
{{ __('Submit') }}
</button>
</form>
Once the user submits a value by pressing the submit button , I want a boolean variable to also update to true , so $book = true.
Once the user has selected value from the dropdown and the boolean value is true. I want the blade layout will appear or even a Div class will appear.
I've tried the below but its not displaying
<?php
if ($book == true)
{
#include 'layouts.divAPIclass');
}
else
{
echo "error";
}
?>
I know this is a lot but if you have any questions just ask. If you have any better ways in doing this please suggest. Thanks
You've got options for this. I don't know what your routes file looks like, but I'm going to assume you have the following in your web routes file.
Route::post('/your/route', 'MatchController#update')->name('dailyMatch');
Option #1:
Redirect to a named route
Your blade that the form is on:
<form method="POST" action="/your/route">
#csrf
<select name="dailyMatch" id="dailyMatch" onchange="this.form.submit()">
<option value="pop">Pop</option>
<option value="classical">Classical</option>
</select>
</form>
#if( $book == true )
#include('layouts.divAPIclass')
#endif
Your MatchController:
public function update(Request $request)
{
$dailyMatch = $request->dailyMatch;
// process your data
...
// then redirect back with your boolean value
return redirect()->route('routenamehere', [
'book' => true,
'dailyMatch' => $dailyMatch
]);
}
Option #2:
Take advantage of laravels back() helper
<form method="POST" action="/your/route">
#csrf
<select name="dailyMatch" id="dailyMatch" onchange="this.form.submit()">
<option value="pop">Pop</option>
<option value="classical">Classical</option>
</select>
</form>
#if( session('dailyMatchUpdated') )
#include('layouts.divAPIclass')
#endif
Your MatchController:
public function update(Request $request)
{
$dailyMatch = $request->dailyMatch;
// Process your dailyMatch data
...
// Then use the back() function
return back()->with('dailyMatchUpdated', 'You selected a new match');
}
Option #3:
Redirect to a controller action
If you are navigating to the original form page via a controller action, I would suggest to go this route
<form method="POST" action="/your/route">
#csrf
<select name="dailyMatch" id="dailyMatch" onchange="this.form.submit()">
<option value="pop">Pop</option>
<option value="classical">Classical</option>
</select>
</form>
#if( $book == true )
#include('layouts.divAPIclass')
#endif
Your MatchController:
public function update(Request $request)
{
$dailyMatch = $request->dailymatch;
// Process your data
...
// Then redirect to the original controller action and pass it the book value
return redirect()->action('SomeController#someFunction', ['book' => true]);
}
Hopefully this helps you out!

Laravel: orderBy like count

Right so on my website, registered users can create posts and like other peoples posts. When displaying all the posts i have options where the users can sort by title, date and like count. I have done the title and date but im having trouble with sorting by like count. What would be the best way to implement this feature into my system.
This is my post controller method for retrieving and ordering the posts:
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['sort'] == "like"){
//how would I go about ordering by like count here
}
return view ('eventspage', ['posts' => $posts]);
}
Here is my view where users select what to order by:
<form action="{{ route('events') }}">
<select name="sort" onchange="this.form.submit()" class="form-control">
<option value="">Sort By</option>
<option value="created_at">Date</option>
<option value="title">Title</option>
<option value="like">Likes</option>
<input type="hidden" name="formName" value="sort">
</select>
</form>
Use this:
$posts = Post::withCount('likes')->orderByDesc('likes_count')->get();
This requires a likes relationship in the Post model:
public function likes() {
return $this->hasMany(Like::class);
}

How to use a variable as "value" attribute in <option> tag

I'm currently using Laravel and I want to have a dropdown box display category names from my database, but when selected the value it returns to the server should be a numerical value of the name selected which is also stored in the database.
Like so:
#foreach($categories as $category)
<option name="pid" value="$category->id" id="cname">{{$category->name}}</option>
#endforeach
The values are passed from my Controller to the Blade template. As you can see, I want it to display the category names in the drop down (which it does fine), but once selected and submitted, I want the category ID to be returned. Since the "value" attribute returns the value, I want to have the variable $category->id as the "value". I want to do this without using JavaScript or jQuery. Only with PHP. How would I go about accomplishing this and is it even possible?
When I try to use value="{{$category->id}}" I get the Laravel error:
Integrity constraint violation: 1048 Column 'parent_id' cannot be null
So it seems like it isn't submitting the value of the dropdown.
Here is the code I'm currently using in my Blade template:
<form class="" action="{{route('createsubcategorypost')}}" method="post">
<div class="form-group">
<label for="cname">Sub-Category name:</label>
<input type="text" name="cname" value="" placeholder="Sub-Category Name" id="cname" class="form-control">
</div>
<div class="form-group">
<label for="pid">Parent ID</label>
<select class="form-control">
#foreach($categories as $category)
<option name="pid" value="{{$category->id}}" id="pid">{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<center>
<button type="submit" name="button" class="btn btn-success">Create Sub-Category</button>
</center>
</div>
{{csrf_field()}}
</form>
And this is the code in my Controller:
public function CreateSubCategoryPost(Request $request){
if ($request->cname == null) {
session()->flash('errormessage',' Invalid sub-category name.');
return redirect()->back();
}
$scc = SubCategory::where('name',$request->cname)->first();
if ($scc !== null) {
session()->flash('errormessage',' Sub-category with that name already exists.');
return redirect()->back();
}
$subCategory = new SubCategory;
$subCategory->name = $request->cname;
$subCategory->uniqueid = 'SCA'.str_random(28);
$subCategory->slug = str_slug($request->cname,'-');
$subCategory->parent_id = $request->pid;
$subCategory->save();
return redirect()->route('categories');
}
Same way you you are displaying the category name inside the option tag :
#foreach($categories as $category)
<option name="pid" value="{{$category->id}}" id="cname">{{$category->name}}</option>
#endforeach
Everything you call from a database in Laravel should have the format {{$category->someName}} no matter where you place it in your view. In your case you need to enclose $category->id in {{ }}

Categories