Laravel search logic - laravel

For the past two days I was trying to build this relatively simple search system but I just can't figure this out..
Basically, I have a few select tags which contain options to filter the users..
Something like this:
<div class="col-sm-4">
<label for="price">Price:</label><br>
<select class="browse-select" name="price">
<option>Any</option>
<option value="1">Less than 100$</option>
<option value="2">More than 100$</option>
</select>
</div>
<div class="col-sm-4">
<label for="delivery">Delivery:</label><br>
<select class="browse-select" name="delivery">
<option>Any</option>
<option value="1">1 month or less</option>
<option value="7">7 days or less</option>
<option value="3">3 days or less</option>
</select>
</div>
Those are in a form (get request form) and here's my controller.
public function index(Request $request){
$users = User::paginate(10);
$service = Service::all();
//Search Logic
$category = $request->input('category');
$price = $request->input('price');
$delivery = $request->input('delivery');
$searchQuery = Service::with('user');
$searchQuery->where('category','=',$category);
if ($price == 1) { //price input has a value of 1 which means (less than 100)
$searchQuery->where('price','<',100)->where('category','=',$category);
}elseif($price == 2){
$searchQuery->where('price','>',100)->where('category','=',$category);
}
$result = $searchQuery->get();
return view('browse.index', compact('users','service','result'));
}
As you can see I have a relationship between Users and Services. Because I need to access user's services in order to compare the values and query the database.
What I have so far, works but only for one select. If I select a category, that works fine and the user is displayed. But, if I try for example to choose a category and also a price then it returns all the users.
How should I do this properly? I feel like I'm missing something here..

I believe you need to add additional checks and split your query. Something like
$searchQuery = Service::with('user');
if($request->has('category'))
{
$searchQuery->where('category', $request->input('category'));
}
if($request->has('price'))
{
$operator = (1 === $request->input('price')) ? '>' : '<';
$searchQuery->where('price', $operator, 100);
}
$result = $searchQuery->get();

Related

How can I store data in multiple rows in my SQL database in Laravel

I'm facing a problem while storing data...I'm using multiselect on my view and selecting multiple courses from that.
This is my View:
<div class="form-group">
<label for="">Select Course </label>
<select class="mul-select" multiple="true" name="course_code[]" id="group"class="form-control">Group ID's
<option value="">Select Course Code</option>
#foreach($courses as $c)
<option value="{{$c->id}}">{{$c->course_title}}</option>
#endforeach
</select>
</div>
My initial controller and it's not dynamic.I can select only there courses and store into my database through three foreign of same table.
public function store(Request $r){
$teacher_id = $r->teacher_id;
$session = $r->session;
$semester = $r->semester;
$course1=NULL;
$course2=NULL;
$course3=NULL;
$size =sizeof($r->course_code);
if($size>0)
$course1 = $r->course_code[0];
if($size>1)
$course2 = $r->course_code[1];
if($size>2)
$course3 = $r->course_code[2];
$obj = new Assigncourse();
$obj->teacher_id = $teacher_id;
$obj->session = $session;
$obj->semester =$semester;
$obj->course1 =$course1;
$obj->course2 = $course2;
$obj->course3 = $course3;
if($obj->save())
{
if($course1!=NULL)
{$affected = DB::table('courses')
->where('id', $course1)
->update(['status' => 1]);
}
if($course2!=NULL)
{$affected = DB::table('courses')
->where('id', $course2)
->update(['status' => 1]);
}
if($course3!=NULL)
{$affected = DB::table('courses')
->where('id', $course3)
->update(['status' => 1]);
}
return redirect()->back()->with('msg','Succesfully Inserted');
}
}

Laravel - Calculate minimum value from multiple fields in controller

I want to calculate the minimum value from a collection of form fields.
I have one-to-many relationship, where one shop can have many items ans that is working fine without any errors.
My form
<form action="{{ route('form_submit') }}" method="post">
#csrf
<h3>Item 1</h3>
<input type="text" name="item[]">
<input type="text" name="price[]">
//Like this I can add many fields
<input type="submit">
</form>
Controller
public function store(Request $request, $id){
$shop = Shop::findorfail($id);
$item = Item::where('shop_id', $shop->id)->get(); //working fine
$i=0;
$price = request('price')
foreach( $items as $item)
$item->price = request('price')[$i];
$i++;
//I tried
$price_group = collect($item->price)->where('shop_id', $shop->id);
$min_price = min($price_group);
$item->save();
}
Route
Route::post('/{id}', 'Controller#store')->name('form_submit');
But it does not calculate the minimum price. When I dd($min_price), its total blank. What am I missing here?
I think is just...
$items = Item::where('shop_id', $shop->id)->get();
$min = $items->min('price');
And take a look on eager loading for relations. It's much better.
I solved this by #Jonas's solution. And I make this my answer.
Controller
public function store(Request $request, $id){
$shop = Shop::findorfail($id);
$item = Item::where('shop_id', $shop->id)->get(); //working fine
$i=0;
$price = request('price')
foreach( $items as $item)
$item->price = request('price')[$i];
$i++;
//This works
$min_price = min(request('price'));
$item->save();
}

Passing in value of object then searching against that object

I have a search working that finds users whose preferences match a landlords property. This is all well and good, but I want the landlord to be able to select a property, then press search, and pass that property object to be compared against.
This is an image of the search
Whichever property is chosen from the list is used to be searched against in the search.
This is the view of the search
<div class="row">
<div class="col-md-10">
<select class="form-control" id="property_address" name="property_address">
<!--Gets all counties from DB -->
#foreach ($properties as $property)
<option value="{{$property->address . ', ' . $property->town . ', ' . $property->county}}">{{$property->address . ', ' . $property->town . ', ' . $property->county}}</option>
#endforeach
</select>
</div> <!-- ./ col-6-->
</div> <!-- ./ row-5 -->
<div class="row mt-md-4">
<div class="col-md-4">
<button type="submit" class="form-control btn btn-primary">
Search
</button>
</div>
</div>
This is the controller
The first part renders the search form
public function searchhome(){
//Search Filter UI
//Populates fields.
$user = Auth::user();
$properties = PropertyAdvert::where('user_id', Auth::id())->get();
return view('pages/account/search/index', compact('user', 'properties'));}
Next is the logic
public function searchresults(Request $request){
//Gets all users that are tenants
$tenants = User::where('userType', 'tenant')->first();
//Gets all preferances
$Prefereances = TenantPreferance::all()->first();
//Gets the prefereances that match a tenant id
$pref = $Prefereances::where('user_id', $tenants->id)->first();
//Gets the current signed in users property
//Attempting to get value of property by name
$property = $request->property_address;
$result = $pref
->where('county' , $property->county)
->where('type' , $property->type)
->where('rent', '<=', $property->rent)
->where('bedrooms', '<=', $property->bedrooms)
->where('bathrooms', '<=', $property->bathrooms);
$users = $result->get();
return view('pages/account/search/results', compact('users'));
}
I tried using the request object to set the selected property as the one being compared against.
Any ideas?
Rather than populating the select value with the address, populate it with the ID of the property, then get that property from the database by the ID passed from the select.
$property = Property::find($request->property_id);
$result = $pref
->where('county' , $property->county)
->where('type' , $property->type)
->where('rent', '<=', $property->rent)
->where('bedrooms', '<=', $property->bedrooms)
->where('bathrooms', '<=', $property->bathrooms);
$users = $result->get();

codeigniter form_dropdown return wrong value

My Model,
function get_partners_name()
{
$q = $this->db->select("id,fname,lname")
->from('partner');
$all_partners = $q->get()->result();
$data = array();
foreach($all_partners as $partner)
{
$data[$partner->id] = $partner->fname.' '.$partner->lname;
}
return $data;
}
my controller var_dump($partners) data is,
array (size=2)
38 => string 'Mahesh' (length=6)
40 => string 'Rahul' (length=4)
My view,
<?php array_unshift($partners, "-Select-");?>
<?php echo form_dropdown('parnter', $partners,'',''); ?>
so in dropdown i want to display,
<option value='0'>-Select-</option>
<option value='38'>Mahesh</option>
<option value='40'>Rahul</option>
But it display,
<option value='0'>-Select-</option>
<option value='1'>Mahesh</option>
<option value='2'>Rahul</option>
from the PHP manual.
'array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.'
so your keys are being renumbered when using unshift.
since the select option should never be selected I would suggest hardcoding it into the view. also don't give it a value if you don't want users to select it.
<select name='foo'>
<option disabled>-Select-</option>
<?php
foreach($partners as $partner){
echo '<option value="';
echo $partner->id;
echo '">';
echo $partner->name;
echo '</option>';
}
?>
</select>

CodeIgniter function for returning special dropdown

I want to create a function in my model that does something a bit different and need a bit of help.
I have a database table with names, description, ids etc etc .... there is only one of each name, but i want to return 3 entries for every 1 name, prefixed with a number on it.
So, for example, if i have 2 entries in my database with the names 'joe' and 'bob' .... i want my dropdown box to look like the following
<select>
<option value="joe1">joe1 - description</value>
<option value="joe2">joe2 - description</value>
<option value="joe3">joe3 - description</value>
<option value="bob1">bob1 - description</value>
<option value="bob2">bob2 - description</value>
<option value="bob3">bob3 - description</value>
and so on for additional entries in the DB.
i understand how to do a normal dropdown box, but not one like this.
Any help would be grand :)
Try something like this:
function get_users()
{
$this->db->select("id,name,desc");
$this->db->from("table_name");
$q = $this->db->get();
$rows = $q->row_array();
}
In controller method:
$data = array();
$data['users'] = $this->model_name->get_users();
$this->load->view('view_name',$data);
In view:
<?php
echo "<SELECT>";
foreach($users as $user)
{
for ($i=1; $i<=3; $i++)
{
$id = $user['id'].$i;
echo '<option value="'.$id.'">'.$id.' - '.$user['desc'].'</option>';
}
}
echo "</SELECT>";
?>

Resources