Skip to content

Instantly share code, notes, and snippets.

@kingsloi
Forked from jeffochoa/EloquentSortableServiceProvider.php
Last active November 29, 2018 16:24
Show Gist options
  • Save kingsloi/313233ba0d963d9172ee36dcbbd57e2c to your computer and use it in GitHub Desktop.
Save kingsloi/313233ba0d963d9172ee36dcbbd57e2c to your computer and use it in GitHub Desktop.
Persistent Laravel filtering, pagination and column sorting link generation using macros

Let's say you have a table, that's sortable (e.g. via table headings), filterable (using your own implementation of whatever it is you are filtering) via $_GET/request()->query parameters. Normally, links that are generated for pagination/sorting do not including any already set query parameters. This request macro fixes that.

Example of the links generated with persistent query parameters for table headings/pagination

// config/app.php
'providers' => [
//...
\App\Providers\SortableServiceProvider::class,
//...
]
{{-- resources/views/pages/index.blade.php --}}
<table>
<thead>
<tr>
<th>
<a href="{{request()->sortBy('title')}}">Title</a>
</th>
<th>
<a href="{{request()->sortBy('slug')}}">Slug</a>
</th>
</tr>
</thead>
<tbody>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
</tbody>
</table>
...
{{ $pages->links() }}
// Http/Controllers/PageController.php
public function index() {
$users = Page::sort()->paginate(10)->appends(request()->query());
return view('pages', compact('pages'));
}
<?php
namespace App\Providers;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\ServiceProvider;
class SortableServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Request::macro('sortBy', function ($field) {
$parameters = request()->query();
if (isset($parameters['sort'])) {
$sort = explode(',', $parameters['sort'], 2);
$order = $sort[1] === 'asc' ? 'desc' : 'asc';
$new = array_merge($parameters, ['sort' => $field . ',' . $order]);
} else {
$new = array_merge($parameters, ['sort' => $field . ',asc']);
}
return request()->fullUrlWithQuery($new);
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment