How to fix search request query problem with multiple form fields - php

I'm working with Laravel 8 and at users.blade.php where all of the users of the website appears, I wanted to add a search form for searching the names, mobile number & other information related to a user:
<form method="GET" action="">
<div>
<div class="form-group">
<div class="row">
<div class="col-md-3">
<label for="name">Name or Last Name</label>
<input type="text" class="form-control" name="name"
value="{{ request()->query('name') }}">
</div>
<div class="col-md-3">
<label for="mnumber">Mobile Number</label>
<input type="text" class="form-control" name="order"
value="{{ request()->query('mnumber') }}">
</div>
<div class="col-md-3">
<label for="ucode">User Code</label>
<input type="text" class="form-control" name="product"
value="{{ request()->query('ucode') }}">
</div>
<div class="col-md-3">
<label for="ncode">National Number</label>
<input type="text" class="form-control" name="order"
value="{{ request()->query('ncode') }}">
</div>
</div>
</div>
</div>
</form>
Then at the Controller I tried this:
public function index()
{
$users = User::query();
if($keyword = request('name')) {
$users->where('name' , 'LIKE' , "%{$keyword}%");
}
$users = $users->latest()->paginate(20);
return view('admin.users.all', compact('users'));
}
But now the problem is when I fill the name field with a user name that already exists in the DB, it does not show that custom user because the if($keyword = request('name')) { condition does not run & request('name') is null!
In other words, when I submit the data using this url:
http://localhost:8000/admin/users?name=ENTERED_NAME&mnumber=&ucode=&ncode=
The result does not appear but when I submit it like this:
http://localhost:8000/admin/users?name=ENTERED_NAME
it shows result correctly!
So how can I properly search for the name field properly while the other fields are in the form?

public function index(Request $request)
{
$users = User::query();
if(isset($request->input('name'))) {
$keyword = $request->input('name');
$users->where('name' , 'LIKE' , "%{$keyword}%");
}
$users = $users->latest()->paginate(20);
return view('admin.users.all', compact('users'));
}

I use when() instead of if.. else.. you could try the query below and check if it works. I use similar types of query to search user.
$user = User::query()
->when(request()->has('name'), function ($query) {
$query->where('name', 'like', '%' . request('name') . '%');
})
->when(request()->has('mnumber'), function ($query) {
$query->where('mnumber', 'like', '%' . request('mnumber') . '%');
})
->when(request()->has('ucode'), function ($query) {
$query->where('ucode', 'like', '%' . request('ucode') . '%');
})
->when(request()->has('ncode'), function ($query) {
$query->where('ncode', 'like', '%' . request('ncode') . '%');
})
->paginate(20);
I think this might work without any modification to the view.

HTML Form Code
<form method="GET" action="">
<div>
<div class="form-group">
<div class="row">
<div class="col-md-3">
<label for="name">Name or Last Name</label>
<input type="text" class="form-control" name="name" value="{{ request()->query('name') }}">
</div>
<div class="col-md-3">
<label for="mnumber">Mobile Number</label>
<input type="text" class="form-control" name="mnumber" value="{{ request()->query('mnumber') }}">
</div>
<div class="col-md-3">
<label for="ucode">User Code</label>
<input type="text" class="form-control" name="ucode" value="{{ request()->query('ucode') }}">
</div>
<div class="col-md-3">
<label for="ncode">National Number</label>
<input type="text" class="form-control" name="ncode" value="{{ request()->query('ncode') }}">
</div>
</div>
</div>
</div>
</form>
Controller Code
Here in your code I suspect issue that in if condition you are not checking double equal you just place single equal. so I resolved it and place.
public function index()
{
$users = User::query();
if($keyword == request('name')) {
$users->where('name' , 'LIKE' , "%{$keyword}%");
}
$users = $users->latest()->paginate(20);
return view('admin.users.all', compact('users'));
}
Modified Controller Code
Here I write code with some Laravel standard and full code for other keywords also.
public function index()
{
$users = User::query();
if($request->has('name')) {
$keyword = $request->input('name');
$users->where('name' , 'LIKE' , "%{$keyword}%");
}
if($request->has('mnumber')) {
$keyword = $request->input('mnumber');
}
if($request->has('ucode')) {
$keyword = $request->input('ucode');
}
if($request->has('ncode')) {
$keyword = $request->input('ncode');
}
$users = $users->latest()->paginate(20);
return view('admin.users.all', compact('users'));
}

Related

Data is not displayed in view Laravel

I am trying to display data from database to detail.blade.php, but no data is displayed in the view.
Here is the detail.blade.php view:
<h6 class="card-title">Order No. {{ $order->order_number }}</h6>
<form>
<div class="form-group">
<label for="date">Date</label>
<input type="text" class="form-control" name="order_date" value="{{ $order->order_date}}" readonly>
</div>
<div class="form-group">
<label for="handle">Handle by</label>
<input type="text" class="form-control" value="." readonly>
</div>
<div class="form-group">
<label for="status">Status</label>
<input type="text" class="form-control" name="status" value="{{ $order->status}}" readonly>
</div>
<div class="form-group">
<label for="subtotal">Subtotal</label>
<input type="text" class="form-control" name="billing_subtotal" value="{{ $order->billing_subtotal}}" readonly>
</div>
</form>
OrderMenuController:
public function show(Order $order)
{
$data = DB::table('order_menu')
->join('menus', 'menus.id', '=', 'order_menu.menu_id')
->join('orders', 'orders.id', '=', 'order_menu.order_id')
->select('orders.*', 'menus.name', 'order_menu.quantity')
->where('orders.id', $order->id)
->get();
return view('admin.order.detail')->with([
'order' => $order,
'data' => $data,
]);
}
And for the route:
Route::namespace("App\Http\Controllers\Admin")->prefix("admin")->name("admin.")->middleware('can:adminpage')->group(function () {
Route::resource("/ordermenu", OrderMenuController::class);
});
Tried dd($order) in the controller, and this is what comes up:
How to solve this? thank you
your dd() shows that you don't have any attributes for the order instance, so it makes sense that you got any result back
Try To change the resource route into orders it might work for you

Requested URL not found on the server in XAMPP using laravel

I tried to edit and updated the employee info, unfortunately, it doesn't work
I fetch the employee id but when I sent the updated data it's not working.
it shows Requested URL not found on the server
this is my controller
public function edit_function($id){
$user = User::find($id);
return view('employee.empedit')->with('user',$user);
}
public function update(Request $request,$id){
$user = User::find($id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->phonenumber = $request->input('phonenumber');
$user->profession = $request->input('profession');
if($request->hasfile('images')){
$file= $request->file('images');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('uploads/user/', $filename);
$user->images= $filename;
}
$user->save();
return redirect('empprofile')->with('success', 'Data Updated.');
}
this is my view
<form method="post" action="/updateimages/{{ $user->id }}" enctype="multipart/form-data">
<div class="container">
<div class="jumbotron">
<h2>Update The Information Of Employee</h2>
{{ csrf_field() }}
{{ method_field('PUT') }}
<div class="form-group">
<label >Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name" value="{{ $user->name }} ">
</div>
<div class="form-group">
<label >Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email" value="{{ $user->email }} ">
</div>
<div class="form-group">
<label >Phone Number:</label>
<input type="text" class="form-control" id="phonenumber" placeholder="Enter Phone Number" name="phonenumber" value="{{ $user->phonenumber }} ">
</div>
<div class="form-group">
<label >Profession :</label>
<input type="text" class="form-control" id="profession" placeholder="Enter Profession" name="profession" value="{{ $user->profession }} ">
</div>
<div class="form-group">
<label >Image :</label>
<input type="file" class="form-control" id="images" placeholder="" name="images" value="{{ $user->images }}">
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit" name="submit" style="width:50%;">Update Data</button>
</div>
</div>
</div>
</form>
this is my route
Route::get('edit_profile/{id}' , "empController#edit_function");
Route::put('/updateimages/{id}', "empController#update");
it shows Requested URL not found on the server
Since I am not a Big fan of Url and id So i will go with
name based routing and Route Model Binding
Step 1: Refactor Routes
Route::get('edit_profile/{user}' , "empController#edit_function")
->name('user.editProfile');
Route::put('/updateimages/{user}', "empController#update")
->name('user.updateProfile');
Step 2: Refactor Controller Method
public function edit_function(User $user)
{
$user = $user;
return view('employee.empedit')->with('user',$user);
}
public function update(Request $request,User $user)
{
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->phonenumber = $request->input('phonenumber');
$user->profession = $request->input('profession');
if($request->hasfile('images')){
$file= $request->file('images');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('uploads/user/', $filename);
$user->images= $filename;
}
$user->save();
return redirect('empprofile')->with('success', 'Data Updated.');
}
Step 3: Edit Html and Switch to route helper
<form method="POST" action="{{route('user.updateProfile',['user' => $user])}}" enctype="multipart/form-data">
Kindly Comment Below if you are facing any issues
Its because some other route replce your existing route. You can solve it by debugging. it will cost your time. I had a better solution,
You name your route. and call the route by route() function.
From your above information,
It may be,
in route ->
Route::put('/updateimages/{id}', "empController#update")->name('updateImage');
in view (form action) ->
<form method="post" action="{{ route('updateImage', $user->id ) }}" enctype="multipart/form-data">

How Can I Prevent Showing Duplicate In foreach loop At Laravel Blade File?

This is my view blade file:
And this is my table data:
This is my view code :
<form action="" method="post">
#csrf
#foreach($options as $opt)
<label for="siteName">site name</label>
<input type="text" id="siteName" name="siteName" value="{{$opt->o_name('siteName')}}">
<label for="siteURL">site url</label>
<input type="text" id="siteURL" name="siteURL" value="{{$opt->o_name('siteURL')}}">
#endforeach
<input type="submit" value="save">
</form>
This is my controller code:
public function viewOptions()
{
$options = Option::all();
return view('view/options', compact('options'));
}
This is my class code:
protected $guarded = [];
public function o_name($val)
{
$valss = DB::table('options')
->select('o_value')
->where('o_name', '=', $val)
->first();
return $valss->o_value;
}
I want to show once in view not duplicate Data and inputs form#
How can I do this? what's the problem with my cods?
I think because you use two input in your #foreach and your foreach loop 2 times..
try this:
<form action="" method="post">
#csrf
#foreach($options as $opt)
<label for="{{ $opt->o_name }}">{{ $opt->o_name }}</label>
<input type="text" id="{{ $opt->o_name }}" name="{{ $opt->o_name }}" value="{{ $opt->o_value }}">
#endforeach
<input type="submit" value="save">
</form>
Update:
if you want to get specific rows, you can just get them you want then pass into view
$options = DB::table('options')
->where('o_name', 'siteName')
->orWhere('o_name', 'siteUrl')
->get();
or wite query builder:
$options = Option::where(function ($q) {
$q->where('o_name', 'siteName')->orWhere('o_name', 'siteUrl');
})->get();
another way is using laravel Scopes
Try with this
<label for="siteName">site name</label>
<input type="text" id="siteName" name="siteName" value="{{$option->o_name('siteName')}}">
<label for="siteURL">site url</label>
<input type="text" id="siteURL" name="siteURL" value="{{$option->o_name('siteURL')}}">
Controller
public function viewOptions()
{
$option = Option::all()->first();
return view('view/options', compact('option'));
}
Update your controller code and replace
$options = Option::all();
with
$options_all = Option::all();
$options=$options_all[0];
the new code will look like this
public function viewOptions(){
$options_all = Option::all();
$options=$options_all[0];
return view('view/options', compact('options'));
}

Search query condition not working - Laravel 5.7

I have this in my view:
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12">
<form class="search-form search-form-basic" action="/candidates/index" method="post">
{{ csrf_field() }}
<div class="form-row">
<div class="col-md-4 form-group">
<label for="search_email">First name:</label>
<input type="text" name="search_first_name" id="search_first_name" class="form-control" #if(isset(Session::get('inputs')['search_first_name'])) value="{{ Session::get('inputs')['search_first_name'] }}" #endif>
</div>
<div class="col-md-4 form-group">
<label for="search_last_name">Last name:</label>
<input type="text" name="search_last_name" id="search_last_name" class="form-control" #if(isset(Session::get('inputs')['search_last_name'])) value="{{ Session::get('inputs')['search_last_name'] }}" #endif>
</div>
<div class="col-md-4 form-group">
<label for="search_round_number">Round Number:</label>
<input type="text" name="search_round_number" id="search_round_number" class="form-control" placeholder="" #if(isset(Session::get('inputs')['search_round_number'])) value="{{ Session::get('inputs')['search_round_number'] }}" #endif>
</div>
<div class="col-md-4 form-group">
<label for="search_location">location:</label>
<input type="text" name="search_location" id="search_location" class="form-control"
#if(isset(Session::get('inputs')['search_location'])) value="{{ Session::get('inputs')['search_location'] }}" #endif>
</div>
<select name="options" class="col-md-4 form-group">
<option value="">--- Select From ---</option>
<option value="birth_date">Birth Date</option>
<option value="CV_grade_date">CV Grade Date</option>
<option value="source">Source</option>
<option value="recommendation">Recommended</option>
<option value="created_at">Applied</option>
</select>
<div class="col-md-4 form-group">
<label for="search_from_date">From:</label>
<input type="date" name="search_from_date" id="search_from_date" class="form-control"
#if(isset(Session::get('inputs')['search_from_date'])) value="{{ Session::get('inputs')['search_from_date'] }}" #endif>
</div>
<div class="col-md-4 form-group">
<label for="search_to_date">To:</label>
<input type="date" name="search_to_date" id="search_to_date" class="form-control"
#if(isset(Session::get('inputs')['search_to_date'])) value="{{ Session::get('inputs')['search_to_date'] }}" #endif>
</div>
</div>
<div class="form-row">
<div class="col-md-12 col-lg-12">
<button type="submit" class="btn btn-custom"><i class="fa fa-search" aria-hidden="true"></i>Search</button>
<i class="fa fa-times-circle" aria-hidden="true"></i>Clear
</div>
</div>
</form>
</div>
My controller:
public function index(Request $request) {
if($request->isMethod('post')){
$search_first_name = $request->search_first_name;
$search_last_name = $request->search_last_name;
$search_email = $request->search_email;
$search_round_number = $request->search_round_number;
$search_location = $request->search_location;
$search_from_date = $request->search_from_date;
$search_to_date = $request->search_to_date;
$options = Input::get('options');
$recOrSource = null;
if($options == 'recommendation' || $options == 'source') {
$recOrSource = Input::get('options');
$options == null;
}
$candidate = DB::table('candidates')
->when($search_first_name, function ($query) use ($search_first_name) {
return $query->where('first_name', 'like', '%' . $search_first_name . '%');
})
->when($search_last_name, function ($query) use ($search_last_name) {
return $query->where('last_name', 'like', '%' . $search_last_name . '%');
})
->when($search_email, function ($query) use ($search_email) {
return $query->where('email', $search_email);
})
->when($search_round_number, function ($query) use ($search_round_number) {
return $query->where('round_number', $search_round_number);
})
->when($search_location, function ($query) use ($search_location) {
return $query->where('location', $search_location);
})
->when($recOrSource, function ($query) use ($recOrSource,$search_from_date,$search_to_date) {
return $query->where(!empty($recOrSource))->whereBetween('created_at', array($search_from_date, $search_to_date));
})
->when($options, function ($query) use ($options,$search_from_date,$search_to_date ) {
return $query->whereBetween($options, array($search_from_date, $search_to_date));
})
->orderBy('first_name', 'asc')
->orderBy('last_name', 'asc')
->get();
Session::flash('inputs', [
'search_first_name' => $search_first_name,
'search_last_name' => $search_last_name,
'search_email' => $search_email,
'search_round_number' => $search_round_number,
'search_from_date' => $search_from_date,
'search_to_date' => $search_to_date,
'search_location' => $search_location
]);
}else{
Session::forget('inputs');
$candidate = Candidate::orderBy('first_name', 'asc')
->orderBy('last_name', 'asc')
->get();
}
return view('/candidates/index', [
'candidate' => $candidate
]);
When I select "source" as one of the options, and enter from-to dates, I'm receiving this error:
Column not found: 1054 Unknown column '1' in 'where clause' (SQL: select * from candidates where 1 is null and created_at between 2015-8-8 and 2019-1-1 and source between 2015-8-8 and 2019-1-1 order by first_name asc, last_name asc)
However, dd($recOrSource) is returning correct value; I don't see where this "1" is coming from, and why this part is run
->when($options, function ($query) use ($options,$search_from_date,$search_to_date ) {
return $query->whereBetween($options, array($search_from_date, $search_to_date));
})
when I have
if($options == 'recommendation' || $options == 'source') {
$recOrSource = Input::get('options');
$options == null;
}

I have the following error: "Type error: Too few arguments to function AlbumController::postEdit(), 1 passed and exactly 2 expected"

I have the following problem when trying to edit an "album", hopefully they can help me, I'm a little frustrated haha.
The Form
<form name="editalbum" action="{{ action('AlbumController#postEdit', $album->id) }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<fieldset>
<h2>Editar <strong>{{$album->name}}</strong></h2>
<br></br>
<div class="form-group">
<label for="name">Nombre del proyecto</label>
<input name="name" type="text" class="form-control" value="{{ $album->name }}" required>
</div>
<div class="form-group">
<label for="description">Descripción del proyecto</label>
<textarea name="description" rows="10" cols="50" type="text" class="form-control" value="{{ $album->description }}" required></textarea>
</div>
<div class="form-group">
<label for="location">Locación:</label>
<input name="location" type="text" class="form-control" value="{{ $album->location }}" required>
</div>
<div class="form-group">
<label for="year">Año:</label>
<input name="year" type="text" class="form-control" value="{{ $album->year }}" required>
</div>
<button type="submit" class="btn btn-primary">Editar</button>
</fieldset>
</form>
So far I think everything is going well because I try to post in the ID of the model.
The function:
public function postEdit(Request $request, $id)
{
$album = Album::find($id);
$album = Album::all();
if(count($album) > 0){
$album->name = Input::get('name');
$album->description = Input::get('description');
$album->year = Input::get('year');
$album->location = Input::get('location');
$album->save();
Alert::success('Successfully Updated', 'Congratulations');
return view('admin.dashboard');
} else {
Alert::error('Facilities not found', 'Error');
return view('galeries');
}
I think you made error in routes.php
It should look like this:
Route::post('albums/update/{id}', ['uses' => 'AlbumController#postEdit']);
One solution will be to remove the DI Request object
public function postEdit($id)
{
//rest of code
}
note: the param has to be passed as a array
action="{{ action('AlbumController#postEdit', ['id' => $album->id]) }}"

Categories