menu

Questions & Answers

laravel orderby tow column date and number

i have laravel relation and this is the model relation

public function get_journal_entry_lines()
{
    return $this->hasMany('App\Models\Journal_entry_line','user_id','id')->orderBy('date','asc')->orderBy('number','asc');
}

now the result come like this

| number|date        |
|-------|------------|
| 1     | 2022-01-01 | 
| 2     | 2022-01-01 | 
| 10    | 2022-01-01 | 
| 12    | 2022-01-01 | 
| 3     | 2022-01-01 |

and i need the data to be like this

| number|date        |
|-------|------------|
| 1     | 2022-01-01 | 
| 2     | 2022-01-01 | 
| 3     | 2022-01-01 | 
| 4     | 2022-01-01 | 
| 5     | 2022-01-01 |

and the relation already order by the date first then the number how can i do that thanks

Answers(2) :
return $this->hasMany(App\Models\Journal_entry_line::class, 'user_id', 'id')
    ->orderBy('number', 'ASC')
    ->orderBy('date', 'ASC');

If you want to order by "number" first, it should be the first in your query.

You can use the orderBy method to sort the results of a query based on multiple columns.

To order the results by two columns, date and number, you can chain multiple orderBy method in your query:

$data = Model::orderBy('date_column', 'desc')->orderBy('number_column', 'asc')->get();

This will first order the results by the date_column in descending order, and then by the number_column in ascending order.

You can also use sortBy in a collection object instead of query builder,

$data = Model::all();
$data = $data->sortByDesc('date_column')->sortBy('number_column');

You can also use the sortBy method with a closure, which allows you to specify a custom sorting algorithm.

$data = $data->sortBy(function ($item) {
    return $item->date_column . ' ' . $item->number_column;
});

It's worth noting that the order of the columns in the orderBy method matters. The first column specified in the method will take precedence over the second column, and so on.