nesh
nesh

Reputation: 71

Sort json object laravel

I have two merged queries and I need to sort (orderBy) by id.

$query1= DB::table('contract')->where('to_user_id',$to_user_id)->get();
$query2= DB::table('contract')->where('from_user_id',$to_user_id)->get();
$query1= $query1->merge($query2);

I tried to orderBy('id') but it ordered individualy not together.

Upvotes: 3

Views: 399

Answers (2)

Sohel0415
Sohel0415

Reputation: 9853

You can use sortBy() to sort the collection and values() method to reset the keys to consecutively numbered indexes -

$query1 = $query1->merge($query2);
$query1 = $query1->sortBy('id');

$query1 = $query1->values()->all();

Upvotes: 0

Darren
Darren

Reputation: 76

Instead of performing 2 queries and merging them, would it be better to just pull the relevant records in 1 go?

For example:

$query1= DB::table('contract')
        ->where('to_user_id',$to_user_id)
        ->orWhere('from_user_id', $to_user_id)
        ->get();

Upvotes: 2

Related Questions