Have you thought about a custom length aware paginatior. https://laracasts.com/discuss/channels/guides/length-aware-paginator
Oct 25, 2017
5
Level 1
Pagination unavailable when filter function is used
Hi everyone: I' stucked once again.
I'm developing a "search" feature. I have a form
This is the view
{{-- Search view --}}
{!! Form::open(['route' =>'admin.properties.search', 'method' => 'GET']) !!}
<div class="form-group">
{!! Form::label('state_id', 'Región')!!}
{!! Form::select('state_id', $states, null, ['class' => 'form-control', 'placeholder' => 'Seleccione una Región', 'required']) !!}
</div>
<div class="form-group">
{!! Form::label('property_type', 'Clase de Propiedad')!!}
{!! Form::select('property_type', ['house' => 'Casa', 'flat' => 'Departamento', 'office' => 'Oficina',
'shop' => 'Local comercial', 'warehouse' => 'Bodega', 'land' => 'Terreno',
'parking' => 'Estacionamiento'], null, ['placeholder' => 'Selecciona un tipo', 'class' => 'form-control', 'required']);!!}
</div>
<div class="form-group">
{!! Form::label('price', 'Precio UF')!!}
{!! Form::text('price', null, ['class' => 'form-control', 'id' => 'price',
'data-slider-min' => '0', 'data-slider-max'=> '100000' , 'data-slider-step'=> '100',
'data-slider-value'=>'[25000,75000]', 'required'] )!!}
</div>
<div class="form-group">
{!! Form::hidden('rent', 0) !!}
{!! Form::checkbox('rent') !!}
{!! Form::label('rent', 'Arriendo')!!}
</div>
<div class="form-group">
{!! Form::hidden('sale', 0) !!}
{!! Form::checkbox('sale') !!}
{!! Form::label('sale', 'Venta')!!}
</div>
{!! Form::submit('Buscar', ['class' => 'btn btn-primary'])!!}
{!! Form::close() !!}
Routes
Route::get('/properties/search', [
'uses' => 'PropertyController@search',
'as' => 'admin.properties.search'
]);
Controllers
public function search(Request $request)
{
$properties = Property::orderBy('updated_at', 'asc')
->whereBetween('price', [$prices[0], $prices[1]])
->where('property_type', $request->property_type)
->get()
->filter(function ($property) use ($request) {
if ($property->building_id) {
return $property->building->neighborhood->place->city->state->id == $request->state_id;
} else {
return $property->neighborhood->place->city->state->id == $request->state_id;
}
});
return view('admin.properties.index')
->with('states', $states)
->with('properties', $properties);
}
The problem: When I click in the "2" or other any number, pagination does not work properly. An error appears and says
ErrorException (E_NOTICE) Undefined offset: 1
I've tried to change the method from GET to POST. but, the error, is "Method not allowed".
How is the right way to approach for doing, what I want to do?. It's amost I can't use filter() and paginate() on a Collection, because i've also tried paginate(6) instead of get()
Thank you all.
TL;DR: How can I display a simple search form, and paginate all the results in a propper way?
Please or to participate in this conversation.