Price range filter using CodeIgniter4 - php

I am trying to create a search with multiple filters, one of the filters is a budget or price filter and I am using dropdown instead of creating a price range bar.
In other words, my budget filters are:-
0-2500000
250000-500000
500000-10000000
10000000-25000000
25000000-50000000
50000000 and above
Here is my code and I need help modifying it. The function in Controller and SQL Query in the model only takes a single budget (price) value and displays the result, instead of taking the budget (price) range and showing the result which comes under that budget (price) range.
What I want to achieve is that when the user selects the budget (price) range in the search form, it should display properties that fall under the selected budget range or price range.
HTML Form
<div class="search__area-inner">
<?= form_open('/home/search_residential'); ?>
<div class="row">
<div class="col-12"><?= csrf_field(); ?></div>
<div class="col-6 col-lg-4 col-md-4">
<div class="form-group">
<select name="budget[]" class="wide select_option">
<option data-display="Select Budget">Select Budget</option>
<option value="0-2500000">less than 25 lacs</option>
<option value="250000-500000">25 to 50 lacs</option>
<option value="500000-10000000">50 lacs to 1 cr</option>
<option value="10000000-25000000">1 cr to 2.5 cr</option>
<option value="25000000-50000000">2.5 cr to 5 cr</option>
<option value="50000000">5 cr +</option>
</select>
</div>
</div>
<div class="col-6 col-lg-4 col-md-4">
<div class="form-group">
<select name="type" class="wide select_option">
<option data-display="Select Property Type">Select Property Type</option>
<option value="Apartments">Apartments</option>
<option value="Bungalow">Bungalow</option>
<option value="Row House">Row House</option>
<option value="Villas">Villas</option>
</select>
</div>
</div>
<div class="col-6 col-lg-4 col-md-4">
<div class="form-group">
<input type="text" class="form-control" id="inputLocation" name="city" value="" placeholder="Enter City" required>
</div>
</div>
<br>
<div class="mx-auto">
<div class="form-group">
<button class="btn btn-primary text-uppercase btn-block"> search
<i class="fa fa-search ml-1"></i>
</button>
</div>
</div>
</div>
<?= form_close(); ?>
</div>
Controller code
public function search_residential() {
$data['getfooter'] = $this->homeModel->getFooterInfo();
$data['getad'] = $this->homeModel->getCarousel();
$data['pagelist'] = $this->pageModel->getPages();
$data['cities'] = $this->db->table('tblcity')->select('*')->get()->getResult();
$params = array(
'budget' => $this->request->getVar('budget'),
'type' => $this->request->getVar('type'),
'city' => $this->request->getVar('city'),
);
$data['search'] = $this->homeModel->getSearch($params);
return view('searchresidential', $data);
}
**Model code**
//Searching residential data
public function getSearch($params) {
$budget = $params['budget'];
$type = $params['type'];
$city = $params['city'];
$builder= $this->db->table('tblresidential');
$builder->select('*');
$builder->where('1 = 1');
if ($budget != '') {
$builder->where('budget', $budget);
}
if ($type != '') {
$builder->where('type', $type);
}
if ($city != '') {
$builder->where('city', $city);
}
return $builder->get()->getResult();
}

Instead of:❌
// ...
$builder->where('budget', $budget);
// ...
Use this:✅
// ...
foreach ($budget as $range) {
$builder->orWhere((function (string $range) {
$limits = array_map(
fn($limit) => floatval($limit),
explode("-", $range)
);
return match (count($limits)) {
1 => ['budget >=' => $limits[0]],
2 => ['budget >=' => $limits[0], 'budget <=' => $limits[1]],
default => ['1 =' => 1]
};
})($range));
}
// ...
Resource: $builder->where() : Associative array method

Related

In laravel how to use if /else in controller

I am trying to pass value from view to controller, but it not working it was sent only "APPROVED"
my view
<div class="form-group row">
<label for="colFormLabelLg" class="col-md-2 col-sm-3 control-label control-label-lg"><b>DIGITAL SIGNATURE</b></label>
<div class="col-md-3">
<div class="form-group" id=digital_signature >
<select class="form-control" name="digital_signature" value="{{ old('digital_signature') }}" required autofocus >
<option value=""></option>
<option style="color:green">WITH DIGITAL SIGNATURE</option>
<option style="color:green">WITHOUT DIGITAL SIGNATURE</option>
</select>
</div>
</div>
</div>
my controller
public function new_approvel_update(Request $request, $id)
{
if($request->digital_signature == 'WITH DIGITAL SIGNATURE')
{
$input= Student::Where('delete_status','NOT DELETED')->find($id);
$input['center_approved'] = strtoupper ('APPROVED');
$input['date_of_join'] = $request->date_of_join;
} elseif($request->digital_signature == 'WITHOUT DIGITAL SIGNATURE') {
$input= Student::Where('delete_status','NOT DELETED')->find($id);
$input['center_approved'] = strtoupper ('NOT-APPROVED');
$input['date_of_join'] = $request->date_of_join;
}
$certificate->save();
return redirect('new_application')->with('success',' APPLICATION APPROVED SUCCESSFULLY .');
}
In option tag of select you haven't use value attribute. so it will pass null to a controller.
Change option tags as below :
<option value="APPROVED" style="color:green">WITH DIGITAL SIGNATURE</option>
<option value="NOT-APPROVED" style="color:green">WITHOUT DIGITAL SIGNATURE</option>
Change in your controller :
if($request->digital_signature == 'APPROVED'){
// your code
}
elseif($request->digital_signature == 'NOT-APPROVED'){
// your code
}

Removing options from subsequent select lists once they are selected

I am using a stats app that will attach players (obtained from data within a database) to particular positions. I want players to disappear from being selected in forthcoming positions if they have already been selected so that the same player cannot be put in two separate positions. Can anyone suggest what to do here
This is the code, which i have summarised
<div class="row">
<div class="col-sm-4">
<label>1. Goalkeeper</label>
</div>
<div class="col-sm-4">
<select class="form-control">
<option value="" disabled selected>Select player</option>
<?php
include('conn.php');
$selectplayer= "SELECT * from panel";
$playerresult=$conn->query($selectplayer);
if(!$playerresult){
echo $conn->error;
}
while ($select=$playerresult->fetch_assoc()){
$identify=$select['id'];
$name=$select['name'];
echo "<option>$identify. $name</option>";
}
?>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<label>2. Right corner back</label>
</div>
<div class="col-sm-4">
<select class="form-control">
<option value="" disabled selected>Select player</option>
<?php
include('conn.php');
$selectplayer= "SELECT * from panel";
$playerresult=$conn->query($selectplayer);
if(!$playerresult){
echo $conn->error;
}
while ($select=$playerresult->fetch_assoc()){
$identify=$select['id'];
$name=$select['name'];
echo "<option>$identify. $name</option>";
}
?>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<label>3. Full back</label>
</div>
<div class="col-sm-4">
<select class="form-control">
<option value="" disabled selected>Select player</option>
<?php
include('conn.php');
$selectplayer= "SELECT * from panel";
$playerresult=$conn->query($selectplayer);
if(!$playerresult){
echo $conn->error;
}
while ($select=$playerresult->fetch_assoc()){
$identify=$select['id'];
$name=$select['name'];
echo "<option>$identify. $name</option>";
}
?>
</select>
</div>
</div>
Create a datalist with your players, and JQuery to remove from it when selected one using onchange() on the input:
function resetPlayerList(pos) {
//Get player name
var player = $('input#' + pos).val();
//If player exists in datalist
if($('option[value="' + player + '"]')) {
//Remove player from datalist meaning other inputs cannot add the player
$('option[value="' + player + '"]').remove();
}
//If changing a player, you need to add the old player back into the datalist. This code does not do that for you.
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<datalist id="players">
<option value="1">
<option value="2">
<option value="3">
<option value="4">
<option value="5">
<!-- etc. -->
</datalist>
<input id="CF" onchange="resetPlayerList('CF')" list="players"> <!-- Center Forward -->
<br/><br/>
<input id="LW" onchange="resetPlayerList('LW')" list="players"> <!-- Left Wing -->
This will remove the player from the list using JavaScript/JQuery.
If you want to change a player after adding them in, you will need to do more work, to first re-add the old set player back to the datalist, before removing the new player from it... does that make sense?
UPDATE
<datalist id="players">
<?php
$players = array(
array(
'name' => 'Player 1'
),
array(
'name' => 'Player 2'
)
);
//$players should be your array/object of players from SQL.
for($players as $player) {
echo '<option value="' . $player['name'] . '" />'; //or $player->name if object
}
?>
</datalist>

Laravel AJAX form (receiving data concern)

I have an issue recieving the data from a form which was modified with AJAX.
I have 2 fields: Cinema and Session.
The Session field updates automatically based on which cinema you have chosen. However, when I try to get the session field's value in my controller, it returns as "" (blank) where-as I want it to return what is actually displayed in the drop down box in the form.
Code:
Script:
<script>
$('#cinema').on('change', function(e){
console.log(e)
var cinema_id = e.target.value;
//ajax
$.get('{{ url('/ajax-subcat') }}?cinema_id=' + cinema_id, function(data){
//success data
console.log(data)
$('#sesh').empty();
$.each(data, function(index, subcatObj){
$('#sesh').append('<option value="'+subcatObj.id+'">'+subcatObj.session_time+'</option>');;
});
});
});
</script>
Controller:
public function cart()
{
$formData = array(
'cinema' => Input::get('cinema'),
'sesh' => Input::get('sesh'),
'ticketType' => Input::get('ticketType'),
'count' => Input::get('count')
);
$cinemaDetails = Cinema::find($formData['cinema']);
$session = Session::find($formData['sesh']);
return view('movies/ticketpage/cart')
->with('formData', $formData)
->with('cinemaDetails', $cinemaDetails)
->with('session', $session);
}
View/Blade file:
<div class="container">
<div class="row">
<div class="col-sm-4">
<h2>{{$movie->title}}</h2>
<img src="/WDAAssign2/Assign2-A/{{ $movie->image }}" height="200" width="150">
<p>{{ $movie->description }}</p>
</div>
<div class="col-sm-4">
<h2>Purchase tickets!</h2>
{!! Form::open(array('action'=>'MoviePageController#cart', 'files'=>true)) !!}
<label>Select a Cinema:</label><br>
<select id = "cinema" name = "cinema">
#foreach ($cinemas as $cinema)
<option value="{{$cinema->id}}">{{$cinema->name}}</option>
#endforeach
</select>
<br>
<label>Select a session:</label>
<br>
<select id = "sesh" name = "sesh">
<option value=""></option>
</select>
<br>
<label>Type of ticket:</label>
<br>
<select id= ="ticketType">
<option value="adult">Adult</option>
<option value="concession">Concession</option>
<option value="children">Children</option>
</select>
<br>
<label>Number of tickets:</label><br>
<select id = "count" name ="count">
#for ($i = 1; $i < 10; $i++)
<option value="{{$i}}">{{$i}}</option>
#endfor
</select>
<br><br>
<input type="submit" value="Submit">
{!!Form::close()!!}
</div>
</div>
</div>
Routes:
Route::post('/movie/ticketpage/cart', 'MoviePageController#cart');

Laravel 5.1 - Store input data in my session

I have a view show.php of my single product, when user click on ADD PRODUCT my controller CartController.php update my session cart and update my cartSession table,
Now i'm tryng to put new data (Color input,Size input, Quantity input) on my session and also in my CartSession table. But i dont know why it doesn't work.
-I think that the principal problem is that $request->get('input') doesn't pass to my CartController.php , i tried to return
$request->all() and there is not nothing.
CartController.php
namespace dixard\Http\Controllers;
use Illuminate\Http\Request;
use dixard\Http\Requests;
use dixard\Http\Controllers\Controller;
use dixard\Product;
use dixard\CartSession;
use dixard\CartItem;
use dixard\Shipping;
use Session;
// i think that all classes are ok
public function add(Product $product, CartSession $CartSession,Request $request)
{
$id = $request->get('id');
$cart = \Session::get('cart');
$product->quantity = $request->get('qty');
$product->size = $request->get('size');
$product->color = $request->get('color');
$cart[$product->id] = $product;
\Session::put('cart', $cart);
return $request->all(); // here i tried to get all inputs but it shows me nothing result
$subtotal = 0;
foreach($cart as $producto){
$subtotal += $producto->quantity * $producto->price;
}
$session_code = Session::getId();
$CartSession = new CartSession();
$session_exist = CartSession::where('session_code', $session_code)->orderBy('id', 'desc')->first();
if (isset($session_exist)) {
$s = new CartSession;
$data = array(
'subtotal' => $subtotal,
);
$s->where('session_code', '=', $session_code)->update($data);
}else {
$CartSession = new CartSession();
$CartSession->session_code = $session_code;
$CartSession->subtotal = $subtotal;
$CartSession->save();
}
//return $cart;
//salveremo tutte le informazioni nel array cart nella posizione slug
foreach($cart as $producto){
$this->saveCartItem($producto, $CartSession->id, $session_code, $cart);
}
return redirect()->route('cart-show');
}
Routes.php
Route::bind('product', function($id) {
return dixard\Product::where('id', $id)->first();
});
Route::get('cart/add/{product}', [
'as' => 'cart-add',
'uses' => 'CartController#add'
]);
show.php view
Get Data about the product is ok, title, description, color avaible, price ecc. all information pass to my view.
{!! Form::open(['route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="id" value="{{$product->id}}">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="p_color">Colore</label>
<select name="color" id="p_size" class="form-control">
#foreach($colors as $color)
<option value="{{ $color->color }}">{{ $color->color }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="size">Size</label>
<select name="size" id="p_size" class="form-control">
<option value="XS">XS</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="qty">Quantity</label>
<select name="qty" id="p_qty" class="form-control">
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
</select>
</div>
</div>
</div>
<div class="product-list-actions">
<span class="product-price">
<span class="amount">{{$product->price}}</span>
<input type="submit" class="btn btn-lg btn-primary" >
ADD PRODUCT
</input>
</div><!-- /.product-list-actions -->
{!! Form::close() !!}
Thank you for your help!
You have to explicitly set the post-method to be "get" or you need to change your router to accept the request as post. Even though you're calling the route by name, Form::open defaults to "POST"
https://laravelcollective.com/docs/5.2/html#opening-a-form
Option 1. Change
Route::get('cart/add/{product}',...
to
Route::post('cart/add/{product}',...
Option 2. Change
{!! Form::open(['route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}
to
{!! Form::open(['method'=>'GET', 'route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}

populating a second select box after selecting a first select box value

I need to select second select box value only after selecting the first select box.I want to insert these values into database.. My view page is below.
<div class="form-group">
<label for="" class="control-label col-xs-2">Country</label>
<div class="col-md-6">
<select class="form-control" id="edu" onChange="EduBackgrd()" name="country">
<option value="">Select</option>
<option value='India'>India</option>
<option value='United States'>United States</option>
<option value='United Kingdom'>United Kingdom</option>
<option value='Canada'>Canada</option>
<option value='Singapore'>Singapore</option>
<option value='Others'>Others</option>
</select>
</div>
</div>
<div class="form-group">
<label for="" class="control-label col-xs-2">Location</label>
<div class="col-md-6">
<select class="form-control" id="edct" name="location">
<option value="">Select</option>
<script>
var eduBak = {};
eduBak['India'] = ['Delhi', 'Mumbai', 'Chennai', 'Kolkata', 'Bangalore', 'Hyderabade', 'Pune'];
eduBak['United States'] = ['Alabama', 'Alaska', 'Arizona'];
eduBak['United Kingdom'] = ['England', 'Northrn Ireland', 'Scotland', 'Wales', 'other'];
eduBak['Canada'] = ['Alberta ', 'Brirish Columbia', 'Manitoba', 'others'];
eduBak['Singapore'] = ['Singapore','others'];
eduBak['Others'] = ['Others']
function EduBackgrd() {
var edu = document.getElementById("edu");
var model = document.getElementById("edct");
var educ = edu.options[edu.selectedIndex].value;
while (model.options.length) {
model.remove(0);
}
var ed = eduBak[educ];
if (ed) {
var i;
for (i = 0; i < ed.length; i++) {
var e = new Option(ed[i], i);
model.options.add(e);
}
}
}
</script>
</select>
</div>
</div>
To insert into database I tried my model as:
public function insert()
{
$data=array(
'Country'=>$this->input->post('country'),
'Location'=>$this->input->post('location'),
);
$this->db->insert('tbl_employer', $data);
}
I'm getting a number while inserting.. I don't know how to set value attribute in the script which I had written for selecting the second select box..How could I fix this problem?
You need to use $.ajax() for this like,
$(function(){
$('#edu').on('change',function(){
$.ajax({
url:'php-page.php', // php page to get options
data:{q:this.value},// passing the value
success:function(data){
$('#edct').html(data);//append options
}
})
});
});
Your php-page.php should look like,
<?php
$eduBak=array();
$eduBak['India'] = ['Delhi', 'Mumbai', 'Chennai', 'Kolkata', 'Bangalore', 'Hyderabade', 'Pune'];
$eduBak['United States'] = ['Alabama', 'Alaska', 'Arizona'];
$eduBak['United Kingdom'] = ['England', 'Northrn Ireland', 'Scotland', 'Wales', 'other'];
$eduBak['Canada'] = ['Alberta ', 'Brirish Columbia', 'Manitoba', 'others'];
$eduBak['Singapore'] = ['Singapore','others'];
$eduBak['Others'] = ['Others'];
$q=isset($_REQUEST['q']) ? $_REQUEST['q'] : '';
$str='';
if($q){
$arr=$eduBak[$q];
if(!empty($arr)){
foreach($arr as $val){
$str.='<option value="'.$val.'">'.$val.'</option>';
}
}
}
echo $str;
exit;
?>
UPDATE: Below is the example of without using PHP
var eduBak = {};
eduBak['India'] = ['Delhi', 'Mumbai', 'Chennai', 'Kolkata', 'Bangalore', 'Hyderabade', 'Pune'];
eduBak['United States'] = ['Alabama', 'Alaska', 'Arizona'];
eduBak['United Kingdom'] = ['England', 'Northrn Ireland', 'Scotland', 'Wales', 'other'];
eduBak['Canada'] = ['Alberta ', 'Brirish Columbia', 'Manitoba', 'others'];
eduBak['Singapore'] = ['Singapore', 'others'];
eduBak['Others'] = ['Others']
$('#edu').on('change',function() {
var edu = document.getElementById("edu");
var model = document.getElementById("edct");
var educ = edu.value;
while (model.options.length) {
model.remove(0);
}
var ed = eduBak[educ];
if (ed) {
var i;
for (i = 0; i < ed.length; i++) {
var e = new Option(ed[i], ed[i]);
model.options.add(e);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="" class="control-label col-xs-2">Country</label>
<div class="col-md-6">
<select class="form-control" id="edu" name="country">
<option value="">Select</option>
<option value='India'>India</option>
<option value='United States'>United States</option>
<option value='United Kingdom'>United Kingdom</option>
<option value='Canada'>Canada</option>
<option value='Singapore'>Singapore</option>
<option value='Others'>Others</option>
</select>
</div>
</div>
<div class="form-group">
<label for="" class="control-label col-xs-2">Location</label>
<div class="col-md-6">
<select class="form-control" id="edct" name="location">
<option value="">Select</option>
</select>
</div>
</div>

Categories