I have an index page where I make the listing of some hospitals with a pagination.
I also have a searchbar where I can write an hospital name and the listing should be updated "in real time" with an AJAX request.
My problem is that I am not able to re-use the laravel pagination object by javascript to create the pagination. And I do not want to manage it by pure javascript/jQuery. At the moment, I'm creating a list of all objects returned. But without pagination (so the list can be huge)
So in my controller I have this function
public function index()
{
$hospitals = Hospital::orderBy('name')->paginate(15);
return view('admin.hospitals.show', compact('hospitals'));
}
In my view (/admin/hospitals/show.blade.php), I'm using this to create a pagination (I want to re-use this on ajax response)
<ul>
@foreach($tasks as $task)
<li>{{ $task->name }}</li>
@endforeach
</ul>
{{ $tasks->links() }}
Which give my this result
When typing in the search bar, this ajax is called
$.ajax({
type: "GET",
url: '/admin/hospitals/search/'+ $('#hospital_search').val().trim(),
success: function (data)
{
if ( data.hospital.length == 0 )
{
$('#hospital_result').html('<div class="alert alert-warning">No hospitals found</div>');
}
else
{
//Actual code that give me the listing without pagination
//Would be nice if I could do something like {{ data.hospital->links() }}
var html = '<ul>';
$.each( data.hospital , function( i , hospital ){
html += '<li><a href="/admin/hospitals/'+ hospital.id +'"><b>' + hospital.name + '</b></a></li>';});
html += '</ul>';
$('#hospital_result').html(html);
}
},
error: function (data)
{
alert('Error:', data);
}
});
And my search function
public function search($term = null)
{
if( !$term )
{
$hospital = Hospital::orderBy('name')->get();
}
else
{
//Get match on name
$hospital = Hospital::where('name' , 'LIKE' , '%'.$term.'%')
->orderBy('name')
->get(); //Should be replaced by ->paginate(15) when JS will be replaced
}
//Return as JSON
return response()->json(['success' => true, 'hospital' => $hospital]);
}
How to use the ->links() on the data object in the ajax response?
Or should I change my logic and load a specific view after ajax request?

$hospital = Hospital::query()->where('name', 'LIKE' "%{$term}%")->paginate($perPage);