Combine the two requests and order them based on created_at in Laravel

I created Models for two tables. Now I want to fulfill the query and combine the results based on created_at.

My queries are:

    $first  =  RequestF::where('userId','=',$userId)->get();
    $second =  RequestS::where('userId','=',$userId)->get();

I can combine them using:

     foreach($first as $f) {
        $second->add($f);
     }

But it just adds $first-objects at the end $second, and I can't get them in order based created_at.

How can I combine these two queries and order them at the same time?
Thank.

Update After the @MargusPala sentence, this is my result after $second->toArray(), but it is strange that one object is not ok !! object number 10:

{
  "status" : "Success",
  "data" : {
"showcases" : {
  "10" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-22 10:51:25",
    "type" : "F"
  },
  "2" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-23 10:14:32",
    "type" : "L"
  },
  "3" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-23 10:15:00",
    "type" : "L"
  },
  "11" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-27 09:54:56",
    "type" : "F"
  },
  "4" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-23 11:22:09",
    "type" : "L"
  },
  "5" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-26 10:42:38",
    "type" : "L"
  },
  "6" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-27 09:59:03",
    "type" : "L"
  },
  "7" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-27 09:59:23",
    "type" : "L"
  },
  "0" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-22 11:26:25",
    "type" : "L"
  },
  "8" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-27 10:05:19",
    "type" : "L"
  },
  "1" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-23 10:13:53",
    "type" : "L"
  },
  "9" : {
    "userName" : "mojtaba_talebii",
    "created_at" : "2015-04-27 10:05:33",
    "type" : "L"
  }
}
  },
 "message" : "Here is results"
}

Which is strange, and more, how can I get the result of an ass JSON Array, not a JSON Object.

+4
1

Laravel sortBy(), . :

$second = $second->sortBy(function($s)
{
    return $s->created_at;
});
+4

Source: https://habr.com/ru/post/1584882/


All Articles