Guest User

Untitled

a guest
Nov 19th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Providers;
  4.  
  5. use Illuminate\Database\Query\Builder;
  6. use Illuminate\Support\Facades\Request;
  7. use Illuminate\Support\ServiceProvider;
  8.  
  9. class EloquentSortableServiceProvider extends ServiceProvider
  10. {
  11. /**
  12. * Bootstrap any application services.
  13. *
  14. * @return void
  15. */
  16. public function boot()
  17. {
  18. Builder::macro('sort', function () {
  19. $sort = explode(',', request()->sort, 2);
  20. if (empty($sort[1])) {
  21. return $this;
  22. }
  23. return $this->orderBy($sort[0], $sort[1]);
  24. });
  25.  
  26. Request::macro('sortBy', function ($field) {
  27. $query = request()->query();
  28.  
  29. // go back to the page 1 and sort by $field asc by default
  30. if (empty($query['sort'])) {
  31. return request()->url() . '?sort=' . $field . ',asc';
  32. }
  33.  
  34. // 'sort' is set but the 'field' is empty ? reload
  35. $sort = explode(',', request()->sort, 2);
  36. if (empty($sort[1])) {
  37. return request()->fullUrl();
  38. }
  39.  
  40. // if the current 'order' is 'asc' then return 'desc' and so.
  41. $sort = '?sort=' . $field . ',' . ($sort[1] == 'asc' ? 'desc' : 'asc');
  42.  
  43. return request()->url() . $sort;
  44. });
  45. }
  46.  
  47. /**
  48. * Register any application services.
  49. *
  50. * @return void
  51. */
  52. public function register()
  53. {
  54. //
  55. }
  56. }
  57.  
  58. // Create this service provider and edit your config/app.php file to add:
  59. 'providers' => [
  60. //...
  61. \App\Providers\EloquentSortableServiceProvider::class,
  62. //...
  63. ]
  64.  
  65. // Usage: call sort() method before the paginate()
  66. Route::get('/', function () {
  67. $users = \App\User::sort()->paginate(10);
  68. return view('users', compact('users'));
  69. });
  70.  
  71. // Then you can easily build the links using the request() helper
  72. // calling the sortBy() method and passing the name of the field of your table
  73.  
  74. <a href="{{request()->sortBy('name')}}">Name</a>
  75.  
  76. // Finally don't forget to add this when you call the links() method to persist the new "sort" param
  77. {{ $users->appends(['sort' => request()->sort])->links() }}
Add Comment
Please, Sign In to add comment