Courses

[NEW] Vue.js 3 + Laravel 11 + Vite: SPA CRUD

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

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 58 courses (1056 lessons, 44 h 09 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord