Laravel Order By Example
November 5, 2024 ยท AI Conversations
### Example
If you have a model, say `User`, and an `is_default` column, you can order your query results based on that column:
$users = User::orderBy('is_default', 'desc')->get();
This will sort the users with `is_default` values set to `1` (or `true`) first, followed by those with `0` (or `false`).
### Explanation
– `'desc'`: Orders the records in descending order, showing `is_default = 1` first.
– `'asc'`: Use this to order in ascending order, showing `is_default = 0` first.
### With Multiple `orderBy` Clauses
If you want to order by `is_default` and another column, you can chain multiple `orderBy` methods:
$users = User::orderBy('is_default', 'desc')->orderBy('name', 'asc')->get();
This example will first order by `is_default`, and then by `name` in ascending order for records with the same `is_default` value.
->get()->map(function ($emailset) {
// Add a custom 'encrypted_id' column
$emailset->encrypted_id = Crypt::encrypt($emailset->id);
return $emailset;
});
Here's how to include `orderBy` in your query:
$emailsets = $emailsets->with('project') // Eager load projects
->orderBy('is_default', 'desc') // Order by is_default
->get()
->map(function ($emailset) {
// Add a custom 'encrypted_id' column
$emailset->encrypted_id = Crypt::encrypt($emailset->id);
return $emailset;
});
This way, `emailsets` will be sorted by the `is_default` column in descending order before being retrieved and mapped with the encrypted ID.