i have a few checkboxes that filter my elements from a database but i don't know how to apply a filter like price with a min value and a max value, since from my view i can pass to the controller only one value of my inputs
For example: i want to apply a price filter between 1000 and 1500 to an element
view:
<li><input type="checkbox" name="price[]" value="1000"> <1.000</li>
<li><input type="checkbox" name="price[]" value="1500">1.000 - 1.500</li>
<li><input type="checkbox" name="price[]" value="2000">1.500 - 2.000</li>
<li><input type="checkbox" name="price[]" value="3000">2.000 - 3.000</li>
<li><input type="checkbox" name="price[]" value="4000">3.000 - 4.000</li>
<li><input type="checkbox" name="price[]" value="5000">4.000 - 5.000</li>
<li><input type="checkbox" name="price[]" value="5000"> >5.000</li>
controller:
public function laptops()
{
$filter = $this->input->post();
$data['laptops_toate'] = $this->emag_model->laptops_toate_grid($filter);
$this->load->view('emag/laptops',$data);
model:
public function laptops_toate_grid($filter = null){
$this->db->select('*')
->from('laptop_notebook')
->join('brands','brands.id_brands = laptop_notebook.brand');
if($filter['price']){
$this->db->where('price <', $filter['price']);
}
$query = $this->db->get()->result();
return $query;
}
For just an idea of how you could do it.
The view file:
<li><input type="checkbox" name="price[]" value="<1000"> <1.000</li>
<li><input type="checkbox" name="price[]" value="1000-1500">1.000 - 1.500</li>
<li><input type="checkbox" name="price[]" value="1500-2000">1.500 - 2.000</li>
<li><input type="checkbox" name="price[]" value="2000-3000">2.000 - 3.000</li>
<li><input type="checkbox" name="price[]" value="3000-4000">3.000 - 4.000</li>
<li><input type="checkbox" name="price[]" value="4000-5000">4.000 - 5.000</li>
<li><input type="checkbox" name="price[]" value=">5000"> >5.000</li>
The controller remains the same.
The model becomes:
public function laptops_toate_grid($filter = null){
$this->db->select('*')
->from('laptop_notebook')
->join('brands','brands.id_brands = laptop_notebook.brand');
if (isset($filter['price'])) { // make sure there is price key
$filters = array(); // this is where we store the filters
foreach ($filter['price'] as $price) { // iterate through prices
if ($filter['price'][0] == '<') { // is less
$filters[] = 'price < ' . (int)substr($price, 1);
}
elseif ($filter['price'][0] == '>') { // is more
$filters[] = 'price > ' . (int)substr($price, 1);
}
else { // is between
$expl = explode('-', $price);
$filters[] = 'price BETWEEN ' . (int)$expl[0] . ' AND ' . (int)$expl[1];
}
}
if ($filters) { // if there are filters, create the query
$query = implode(' OR ', $filters);
$query = '('. $query . ')';
$this->db->where($query, false); // false makes sure the query is not escaped
}
}
$query = $this->db->get()->result();
return $query;
}
Note: this is just a working idea, I haven't been tested the code.
Related
I want get product by price
low price and max price
but result has mistake
in my product model
public function scopeminPrice(Builder $query, $min_price): Builder
{
return $query->where('price', '>=', ($min_price));
}
public function scopemaxPrice(Builder $query, $max_price): Builder
{
return $query->where('price', '<=', ($max_price));
}
and my controller
public function index(Request $request)
{
$products = QueryBuilder::for(Product::class)
->allowedFilters([
AllowedFilter::scope('min_price' ),
AllowedFilter::scope('max_price' ),
])
->with('category')->paginate('4')
->appends(request()->query());
return view('frontend.product.index',
compact(
'products',
));
}
and my form
<form method="GET" id="jobfilter-form" enctype="multipart/form-data" content="{{ csrf_token() }}">
<div class="shop-box-area">
<ul class="list-body">
<li>
<input class="form-control" type="text" id="minPrice" name="minPrice" value="" #if ((explode(',', request()->input('filter.min_price')))) #endif oninput="this.nextElementSibling.value = this.value" placeholder="min price">
</li>
<li>
<input class="form-control" type="text" id="maxPrice" name="maxPrice" value="" #if ((explode(',', request()->input('filter.max_price')))) #endif oninput="this.nextElementSibling.value = this.value" placeholder="max price">
</li>
</ul>
</div>
<button class="btn btn-light btn-filter" type="button" id="filter">search</button></form>
and scripts
<script>
function getIds(checkboxName) {
let checkBoxes = document.getElementsByName(checkboxName);
let ids = Array.prototype.slice.call(checkBoxes)
.filter(ch => ch.checked == true).map(ch => ch.value);
return ids;
}
function filterResults() {
let minPrice = document.getElementById("minPrice").value;
let maxPrice = document.getElementById("maxPrice").value;
document.location.href = href;
}
$("#jobfilter-form #filter").on("click", e => {
filterResults();
});
</script>
result is not true
for example when min price is 60000 only show 60000 but product have 50000 and 45000
I am not sure but reason may be the type of your request variables.
Validate as integers "price", "min_price" and "max_price" or specify the type like that;
return $query->where('price', '>=', (int)($min_price));
I want to fetch the corresponding value of my dropdown the image below shows the form and the database. the table was inside the javascript and Iam having a dificult time in figuring out this problem. please help me how to solve this problem... Thank you very much in advance...
Database
forms entry
My Controller
function getFeetypeEndDate() {
$feetype_id = $this->input->get('feety_id[]');
$data = $this->feegroup_model->getFeetypeByEndDate($feetype_id);
echo json_encode($data);
}
My Model
public function get($id = null) {
$this->db->select()->from('feetype');
$this->db->where('is_system', 0);
if ($id != null) {
$this->db->where('id', $id);
} else {
$this->db->order_by('id');
}
$query = $this->db->get();
if ($id != null) {
return $query->row_array();
} else {
return $query->result_array();
}
}
My Javascript in the View Section
<script>
$(document).ready(function (){
$("body").on('click', '.btn-add-more', function (e) {
e.preventDefault();
var amount = $("#amount").val();
var penalty = $("#penalty").val();
var $sr = ($(".jdr1").length + 1);
var rowid = Math.random();
var $html = '<tr class="jdr1" id="' + rowid + '">' +
'<td><span class="btn btn-sm btn-default">' + $sr + '</span><input type="hidden" name="count[]" value="'+Math.floor((Math.random() * 10000) + 1)+'"></td>' +
'<td><select id="feetype_id[]" name="feetype_id[]" class="form-control" >' +
'<?php foreach ($feetypeList as $feetype) { ?>' +
' <option value="<?php echo $feetype['id'] ?>" ' +
'<?php if (set_value('feetype_id[]') == $feetype['id']) { echo "selected =selected"; } ?>><?php echo $feetype['type'] ?></option> <?php $count++; } ?> </select></td>' +
'<td><input type="text" id="startDate" name="startDate" value="<?php echo date($this->customlib->getSchoolDateFormat($feetype->start_date), $this->customlib->dateyyyymmddTodateformat($feetype->start_date)); ?>" placeholder="Start Date" class="form-control input-sm"/></td>' +
'<td><input type="text" id="endDate" name="endDate" value="<?php echo date($this->customlib->getSchoolDateFormat($feetype->end_date), $this->customlib->dateyyyymmddTodateformat($feetype->end_date)); ?>" placeholder="End Date" class="form-control input-sm"/></td>' +
'<td><input type="text" name="amount_td[]" placeholder="Amount" class="form-control input-sm" value="'+amount+'"></td>' +
'<td><input type="text" name="penalty_td" placeholder="Penalty" class="form-control input-sm" value="'+penalty+'"></td>' +
'</tr>';
$("#table-details").append($html);
});
$("body").on('click', '.btn-remove-detail-row', function (e) {
e.preventDefault();
if($("#table-details tr:last-child").attr('id') != 'row1'){
$("#table-details tr:last-child").remove();
}
});
});
jobs.edit.blade.php can be accessed by registered users
out of them the accountant can access some checkboxes(only visible to him)
The database values are changed(Boolean) according to checkboxes submitted by the accountant.
#can ('isAccountant')
//some code with checkboxes
#endcan
The problem is, when a registered user access jobs.edit.blade.php
and submits(Checkboxes are not visible), all the Boolean values in the database becomes Zero
How can i avoid this situation
jobs.edit.blade.php
#can ('isAccountant')
<div class="row">
<div id="status">
#if ($job->entered_status == '0')
<input type="checkbox" name="entered_status" #if($job->entered_status) checked #endif> Entered <br><br>
#elseif ($job->entered_status == '1')
<input type="checkbox" name="entered_status" checked value="1" disabled> Entered <br><br>
<input type='hidden' name='entered_status' value="1">
#endif
#if ($job->sales_status == '1')
<input type="checkbox" name="despatch_status" checked value="1" disabled> All Despatches Completed <br><br>
<input type="checkbox" name="invoice_status" checked value="1" disabled> All Invoices Completed
<input type='hidden' name='despatch_status' value="1">
<input type='hidden' name='invoice_status' value="1">
#endif
#if ($job->sales_status == '0' && $job->job_status == 'Completed' && $job->despatch_status == '0')
<input type="checkbox" name="despatch_status" #if($job->despatch_status) checked #endif value="1"> All Despatches Completed <br><br>
#endif
#if ($job->sales_status == '0' && $job->job_status == 'Completed' && $job->despatch_status == '1')
<input type="checkbox" name="despatch_status" checked value="1"> All Despatches Completed <br><br>
<input type="checkbox" name="invoice_status" #if($job->invoice_status) checked #endif value="1"> All Invoices Completed <br><br>
#endif
</div>
</div>
#endcan
JobController.php
public function update(Request $request, $id)
{
$job = Job::find($id);
$job->customer_name = $request->customer_name;
$job->company_name = $request->company_name;
$job->job_type = $request->job_type;
$job->job_owner = $request->job_owner;
$job->job_status = $request->job_status;
$job->despatch_status = $request->has('despatch_status');
$job->invoice_status = $request->has('invoice_status');
if ($job->despatch_status == 1 && $job->invoice_status == 1) {
$job->sales_status = 1;
}
$job->entered_status = $request->has('entered_status');
AuthServiceProvider.php
public function boot()
{
$this->registerPolicies();
Gate::define('isAdmin', function ($user) {
return $user->user_type == 'Admin';
});
Gate::define('isDirector', function ($user) {
return $user->user_type == 'Director';
});
Gate::define('isProduction', function ($user) {
return $user->user_type == 'Production';
});
Gate::define('isAccountant', function ($user) {
return $user->user_type == 'Accountant';
});
}
Extended Error
_token
"nzY5y8EW5yupkL3d6aL9bcpZRYmlc5YTN94ee1uI"
_method
"PATCH"
id
"10725"
customer_name
""
company_name
""
job_type
"""
Item:\r\n
Qty:\r\n
Size:\r\n
Paper:\r\n
Print:\r\n
Each:\r\n
Total:
"""
job_owner
"Sam"
job_status
"Pending"
job_delivery_date
""
job_delivery_time
""
pk_pkl
"PKL"
entered_status
"on"
The reason for this is that you are using:
$job->despatch_status = $request->has('despatch_status')
$request->has('despatch_status') is true if the request has the field, and false if the request does not have the field.
The code i can recommend:
This will get the despatch_status from the request, if its true or false (or 1/0) it will get passed to $job->despatch_status.
But if despatch_status is not present in the request, the ->get() will return null, so the ?? operator will then read the value already in the database, so then it wont change.
$job->despatch_status = $request->get('despatch_status') ?? $job->despatch_status;
Based on the comments of the other answer, add this to your RouteServiceProvider:
public function boot()
{
//
parent::boot();
if (!$this->app->runningInConsole()) {
foreach (request()->all() as $key => $value) {
if (is_string($value) && $value === 'on') {
request()->offsetSet($key, true);
}
}
}
}
What this will do is scan all incoming fields, and if they are 'on' they get cast to true.
(the reason we add this to a service provider and not middleware is based on order of execution)
I have a textbox that I'm trying to use to search through the database, What I'm trying to achieve is when I type in a date of birth(e.g 14/06/1996) into the textbox(searchdob) it will display the users that have this date of birth value in the database. I've tried use my AppointmentController to do the where conditions so the foreach loop is kept tidier.
Error is: Non-static method Symfony\Component\HttpFoundation\Request::get() should not be called statically, assuming $this from incompatible context
AppointmentController
function addAppointment()
{
$doctors = Doctor::all();
$search = Request::get('searchdob');
$users = User::where('role', '=', 1)
->where('dateofbirth', 'LIKE', '%'.$search.'%')
->get();
return view('appointment/addappointmentform',['users'=>$users],['doctors'=>$doctors]);
}
addappointment.blade
<form>
Insert Patients date of birth
<input
type="text"
name="searchdob"
id="searchdob"
placeholder="dd/mm/yyyy"
onkeyup="
var v = this.value;
if (v.match(/^\d{2}$/) !== null) {
this.value = v + '/';
} else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
this.value = v + '/';
}"
maxlength="10"
></form>
<fieldset>
<legend>Select the Patient</legend>
#foreach($users as $user)
<div>
<label for="dirBtn{{$user->id}}">
<input id="dirBtn{{$user->id}}" type="radio" name="user" value="{{$user->id}}">
{{$user->firstname}}
</label>
</div>
#endforeach
</fieldset>
Change it to:
$search = request('searchdob');
I have a blade file has the user information
{{$user -> name}}
{{$user -> age}}
{{$user -> gender}}
also I have a form to add the permissions for this user
{!! Form::open(['method' => 'post'])!!}
<div>
<label >
<input type="checkbox" value="1"> Setting
</label>
<label >
<input type="checkbox "value="1"> Users
</label>
<label>
<input type="checkbox" value="1"> Images
</label>
</div>
<br>
{!! Form::submit('Save')!!}
{!! Form::close()!!}
and I send the id of the user by routes like this
Route::post('roles/{$user-> name}','control#save_roles');
to this function to save it
public function save_roles(Request $request,$id)
{
$role = new Role;
$role -> user_id = $user -> name;
if($request ->has('setting')){$role ->setting = 1;}
if($request ->has('users')){$role ->users = 1;}
if($request ->has('images')){$role ->images = 1;}
$role -> save();
return redirct('users');
}
but not work
I think your route should be
Route::post('roles/{$userId}','control#save_roles');
and your controller function
public function save_roles(Request $request, $userId)
{
$role = new Role;
$role->user_id = $userId;
.
.
.
}
You have done something wrong here maybe:
public function save_roles(Request $request,$id)
{
$role = new Role;
$role->user_id = $request->name;
if($request->has('setting')){$role->setting = 1;}
if($request->has('users')){$role->users = 1;}
if($request->has('images')){$role->images = 1;}
$role->save();
return redirct('users');
}
OK, you have several issues that need to be fixed.
First, let's fix your route:
Route::post('roles/{username}','control#save_roles');
Then your form, needs an action to POST information to:
{!! Form::open(['method' => 'post','action'=>['control#save_roles',$user->name]])!!}
<div>
<label >
<input type="checkbox" value="1"> Setting
</label>
<label >
<input type="checkbox "value="1"> Users
</label>
<label>
<input type="checkbox" value="1"> Images
</label>
</div>
<br>
{!! Form::submit('Save')!!}
{!! Form::close()!!}
Finally, in your Controller action:
public function save_roles(Request $request,$username)
{
$role = new Role;
$role -> user_id = $username;
if($request ->has('setting')){$role ->setting = 1;}
if($request ->has('users')){$role ->users = 1;}
if($request ->has('images')){$role ->images = 1;}
$role -> save();
return redirect('users');
}