Add sorting to spendings.index route
MODIFY
app/Http/Controllers/SpendingsController.php
app/Http/Controllers/SpendingsController.php
@@ -21,10 +21,29 @@ class SpendingsController extends Controller {
$currentPage = $request->get('page');
}
+ $sort = null;
+
+ $sortColumn = 'date';
+ $sortDirection = 'DESC';
+
+ if ($request->has('sort')) {
+ $sort = $request->get('sort');
+
+ $parts = explode('-', $sort);
+
+ $sortColumn = $parts[0];
+ $sortDirection = $parts[1];
+
+ if ($sortColumn == 'price') {
+ $sortColumn = 'amount';
+ }
+ }
+
return view('spendings.index', [
- 'spendings' => $user->spendings()->offset($currentPage * $limit - $limit)->limit($limit)->get(),
+ 'spendings' => $user->spendings()->orderBy($sortColumn, $sortDirection)->offset($currentPage * $limit - $limit)->limit($limit)->get(),
'currentPage' => $currentPage,
- 'totalPages' => ceil($user->spendings->count() / $limit)
+ 'totalPages' => ceil($user->spendings->count() / $limit),
+ 'sort' => $sort
]);
}

MODIFY
resources/views/spendings/index.blade.php
resources/views/spendings/index.blade.php
<h1>Spendings</h1>
</div>
<div class="wrapper spacing-top-large spacing-bottom-large">
+ <div class="spacing-bottom-large text-align-center">
+ {!! ($sort == 'date-asc') ? '<span>' : '<a href="/spendings?sort=date-asc">' !!}Sort by Date <i class="fa fa-arrow-up"></i>{!! ($sort == 'date-asc') ? '</span>' : '</a>' !!} &middot;
+ {!! ($sort == 'date-desc' || !$sort) ? '<span>' : '<a href="/spendings?sort=date-desc">' !!}Sort by Date <i class="fa fa-arrow-down"></i>{!! ($sort == 'date-desc' || !$sort) ? '</span>' : '</a>' !!} &middot;
+ {!! ($sort == 'price-asc') ? '<span>' : '<a href="/spendings?sort=price-asc">' !!}Sort by Price <i class="fa fa-arrow-up"></i>{!! ($sort == 'price-asc') ? '</span>' : '</a>' !!} &middot;
+ {!! ($sort == 'price-desc') ? '<span>' : '<a href="/spendings?sort=price-desc">' !!}Sort by Price <i class="fa fa-arrow-down"></i>{!! ($sort == 'price-desc') ? '</span>' : '</a>' !!}
+ </div>
<div class="box">
@foreach ($spendings as $spending)
<div class="section row">
@endforeach
</div>
<div class="spacing-top-large text-align-center">
- {!! ($currentPage > 1) ? '<a href="/spendings?page=' . ($currentPage - 1) . '">Previous</a> &middot;' : '' !!} Page {{ $currentPage }} of {{ $totalPages }} {!! ($currentPage < $totalPages) ? '&middot; <a href="/spendings?page=' . ($currentPage + 1) . '">Next</a>' : '' !!}
+ {!! ($currentPage > 1) ? '<a href="/spendings?page=' . ($currentPage - 1) . ($sort ? '&sort=' . $sort : '') . '">Previous</a> &middot;' : '' !!} Page {{ $currentPage }} of {{ $totalPages }} {!! ($currentPage < $totalPages) ? '&middot; <a href="/spendings?page=' . ($currentPage + 1) . ($sort ? '&sort=' . $sort : '') . '">Next</a>' : '' !!}
</div>
</div>
@endsection

Add sorting to spendings.index route