Courses

Vue.js 3 + Laravel 11 + Vite: SPA CRUD

Sorting Data by Clicking Column Headings

Summary of this lesson:
- Adding column-based sorting functionality
- Implementing sorting indicators in table headers
- Managing sort state in Vue component
- Handling sort parameters in Laravel API

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

ordering data


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...

The full lesson is only for Premium Members.
Want to access all 27 lessons of this course? (115 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord