mardi 23 février 2016

Merging two Laravel collections

My head hurts from working with Laravel collections. I have a query:

// Load the user's time sheet and times for this month.
$user = User::find($this->user->id)->with(['timesheets' => function ($query) {
        $query->whereMonth('date', '=', Carbon::now()->month);
    }])->get();
    $user->load('timesheets.times');

$timesheets = $user->pluck('timesheets');

return $timesheets;

This gives me 'date' which is casted as Carbon instance.

[
  [
    {
      date: "2016-02-22 22:05:01",
    },
    {
      date: "2016-02-23 17:08:29",
    }
  ]
]
// And so on ...

I also have a second collection which gives me all dates (Carbon instances) for a given month:

return $days;

[
  {
    date: "2016-02-01 00:00:00",
  },
  {
    date: "2016-02-02 00:00:00",
  },
]
// and so on ...

I would like to either:

  • Create a third collection containing the dates from $timesheets and the dates from $days with any duplicates removed.
  • Filter $days collection with the values from $timesheets and then push/append $days to the $timesheets collection.

I've been looking at Laravel's the push method and the map method, but have so far not nailed it.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire