Hi Everyone: I'm kind of stuck with something.
The Problem: I'm trying, with a html form, building a search feature to my "Property" model. There are several filters, like price, property_type, and so on. One of the main filters, is where is located this Property.php; A property_type could be a warehouse, a house, an apartment. This is the main issue; a house belongs to a Neighborhood.php, but an apartment belongs to a Building.php and Building.php belongs to a Neighborhood.
I other words:
- a) If it is a house: Property->neighborhood()->city()
- b) If it is an apartment: Property->building()->neighborhood()->city()
My Models
// Property.php
class Property extends Model{
public function building()
{
return $this->belongsTo('App\Building');
}
public function neighborhood()
{
return $this->belongsTo('App\Neighborhood');
}
}
<!-- The search form -->
<form method="GET" action="">
<select class="form-control" name="city_id" id="city" data-required>
<option value="">Select a state</option>
@foreach($cities as $city)
<option value=""></option>
@endforeach
</select>
<select class="form-control property_type" name="property_type"
id="property_type"
data-required>
<option value="">Select an option</option>
<option value="house" >House</option>
<option value="apartament" >Apartament
</select>
<!-- some other filters -->
<input type="checkbox" id="sell" name="sell"><label>Venta</label>
<input type="checkbox" id="rent" name="rent"><label>Arriendo</label>
<button type="submit" class="btn btn-primary">Buscar</button>
</form>
// My PropertyController
public function search(PropertySearchRequest $request)
{
$data['cities'] = City::all();
$prices = explode(",", $request->price);
/*Obtener por rango de precio*/
$properties = Property::where('price', '>=', $prices[0])
->where('price', '<=', $prices[1])
->where('property_type', $request->property_type);
if($request->rent == 'on' && $request->sell == 'on'){
$data['properties'] = $properties->paginate(8);
return view('properties.search', $data);
}
if($request->rent == 'on'){
$propiedades = $properties->where('rent', true);
$data['properties'] = $properties->paginate(8);
return view('properties.search', $data);
}
if($request->sell == 'on'){
$properties = $properties->where('sell', true);
$data['properties'] = $properties->paginate(8);
return view('properties.search', $data);
}
}
As you can see, I can filter, everything but City where the preporty belongs
QUESTION: HOW CAN I ACHIEVE THIS AND PAGINATE THE RESULT IN A VIEW?
First Approach:
$properties = $properties->filter(function ($property, $key) use ($request) {
if ($property->building_id) {
return $propiedad->building()->first()->neighborhood()->first()->city()->first()->id == $request->city_id;
} else {
return $propiedad->neighborhood()->first()->city()->first()->id == $request->city_id;
}
});
But I couldn't paginate this
Can anybody help me, please?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire