Laravel working with collection filter and map

January 12, 2019, at 1:20 PM

I have a method where I can return the upcoming payment date. In the below example, getNextDate() will return a Carbon date, like so:

Carbon @1549788696 {#1119 ▼
  date: 2019-02-10 08:51:36.0 UTC (+00:00)

I basically have a bunch of subscriptions in the database, and I want to show only one result in my view, of the next upcoming payment date.

Example, let's say I have three subscriptions:

Subscription 1, getNextDate() will return: 2019-02-18
Subscription 2, getNextDate() will return: 2019-02-10
Subscription 3, getNextDate() will return: 2019-02-25

Since Subscription 2 is the next upcoming that needs to be paid, I want to show only that one, in a widget in my view. How would I go about it? Using filter or map for example, like below?

$subscriptions = auth()->user()->subscriptions()->get();
$filtered = $subscriptions->filter(function ($subscription) {
    return $subscription->getNextDate();

This will just return all of them. But is there a way I can filter it so I get one result only, for the next closest getNextDate()? Or should I do this way differently? Any suggestions will do.

PS. The getNextDate() simply grabs the start_date for a subscription, then calculates the difference in months from Carbon::now() and checks how many payments have been made until now, and then returns the next upcoming payment date. So nothing fancy going on there.

Answer 1

I don't think you need to use filter() here. I think the following should work.

$subscriptions = auth()->user()->subscriptions()->get();
$next = $subscriptions->sortBy(function ($subscription) {
    return $subscription->getNextDate()->timestamp;

You need to sort your collection by ascending order of the next date and get the first item.

How to make query-selector work inside php and calculate?

How to make query-selector work inside php and calculate?

I took a look at this job pricing calculator I found on Codepen and I made it work exactly how it's shown on the pen but I wanted to take it one step furtherI wanted to tie this in with phpmailer but the issue I am having is that the query selector script...

Length of array saved in entry 0?

Length of array saved in entry 0?

i read information out of a MSSQL database and save this into arrays with a length of 2000When i echo the entries i get the length of these arrays in the first entry (e