How do you sort results using Eloquent?

How do you sort results using Eloquent?

In Laravel’s Eloquent, sorting query results is simple with the orderBy method. For example, if you want to order results by a specific column, you can do:

Example

<?php
$results = Model::orderBy('column_name', 'asc')->get();
?>

In this code:

  • Replace 'column_name' with the actual column you want to sort by.
  • The second argument, 'asc' or 'desc', determines whether the results are sorted in ascending or descending order.

You can also sort by multiple columns by chaining orderBy methods like this:

Example

<?php
$results = Model::orderBy('first_column', 'asc')
                ->orderBy('second_column', 'desc')
                ->get();
?>

This allows you to define a primary and secondary sorting criterion, making your queries more flexible.

Related Questions & Topics

Powered and designed by igetvapeaustore.com | © 2024 codestap.com.