In this tutorial, we will improve the posts table by adding the sorting feature.

Back-end: Sorting in Laravel
We will start from the back-end.
app/Http/Controllers/Api/PostController.php:
class PostController extends Controller{ public function index() { $orderColumn = request('order_column', 'created_at'); $orderDirection = request('order_direction', 'desc'); $posts = Post::with('category') ->when(request('category'), function (Builder $query) { $query->where('category_id', request('category')); }) ->orderBy($orderColumn, $orderDirection) ->paginate(10); return PostResource::collection($posts); }}
We will pass the order_column and order_direction as parameters from the URL. The default values will be "created_at" and "desc".
Now we need to add validation for security reasons, to check if those parameters have valid values.
app/Http/Controllers/Api/PostController.php:
class PostController extends Controller{ public function index() { $orderColumn = request('order_column', 'created_at'); if (! in_array($orderColumn, ['id', 'title', 'created_at'])) { $orderColumn = 'created_at'; } $orderDirection = request('order_direction', 'desc'); if (! in_array($orderDirection, ['asc', 'desc'])) { $orderDirection = 'desc'; } $posts = Post::with('category') ->when(request('category'), function (Builder $query) { $query->where('category_id', request('category')); }) ->orderBy($orderColumn, $orderDirection) ->paginate(10); return PostResource::collection($posts); }}
Composable Parameters and Vue Variables
Now, similarly as we did with the category, we need to...
In this article was missed how to fix pagination. If you have 100 items, each page contains 10 items, and will order by id desc list will starts from 100, but if you go to 2nd page you will miss counting and it will show you list start from 20 to 30.
Use the Limit property https://laravel-vue-pagination.org/guide/api/props.html#limit
it's not very convenient to manually create query parameters by concatenation, axios has params options as second params. details: https://axios-http.com/docs/req_config