Create a PHP Array with values from months past the year Using the Carbon API

Asked

Viewed 420 times

0

I need to create a chart of reports from the beginning of the year to the present day. And my idea is to use a line chart that shows each month the value of a report defined by myself.

Example: in the month of January I sold 50 products, and in the month of February I sold 52 products, in the chart will appear only the month of January, February and the following month (current month, as an example).

To get the dates I’m using the Carbon API Here and to get the value of data from one month to the next, I am using an example below done by myself:

$quantidadeMesPassado = Produto::where(['teste'=>$teste])
             ->whereBetween('updated_at',[$comecoMes, $fimDoMes])
             ->get()
             ->count();

To $quantidadeMesPassado takes the value in the database with one condition, the $comecoMesPassado has the beginning of the month with the Carbon and the $fimDoMes owns the end of the month as shown below.

$comecoMes = Carbon::now()->startOfMonth();
$fimDoMes =  Carbon::now()->endOfMonth();

But I’m doubtful to execute to create a array of PHP and spend every month from the beginning of the year until now (today is July, the array should not have August and other months ahead), automatically.

Below is an example I’m using in my code to get the value of the month.

$comecoJaneiro = new Carbon('first day of January');
$comecoFevereiro = new Carbon('first day of February');
$mes = $comecoJaneiro->month;

At first, I think the $quantidadeMesPassado may be a array that possesses the values of $comecoMes and $fimDoMes of all previous months of the current month. Doubt is how to know which are all previous months. For what $comecoMes and $fimDoMes be the array possessing all beginnings of previous month and end of month.

What would be the alternative that could be using to take the value of each previous month and insert within one array?

  • vc just want a list with all months of the year from January to the current month? or full name in Portuguese?

  • that, necessarily yes. I don’t know if it would be something giant to do that.

  • You have to exemplify this array editing your question?

  • Okay, I just edited, at first the question is how to know all the previous months and insert in an array, to be exchanged with $comecoMes and $fimDoMes

2 answers

1


Solution:

$quantitativo = [];

// Com essa expressão no for é possível gerar datas do mês atual até o inicio do ano
foreach(range(0, date('m') -1) as $i) {
    $data = Carbon::today()->subMonths($i);

    $inicio = $data->startOfMonth();
    $fim    = $data->endOfMonth();

    $qtde = Produto::where(['teste'=>$teste])
             ->whereBetween('updated_at',[$inicio, $fim])
             ->count(); // Repare que estou usando o count do query builder e não da collection como você estava usando

     $quantitativo[] = [
         'data' => $inicio,
         'total' => $qtde
     ];
}

As specified in the question the solution is this or near that, although a better solution would be to generate the quantitative all in a single query, why this way in the worst-case scenario will run 12 querys

  • Great algorithm, gave me a great basis of how to accomplish. At first I was looking for something simple anyway. Thankful

1

Taking advantage of your code taking into account that it is a date type in your Where I inform you the following code

$datas = [
       //Caso precise das horas então só passar no formart H-i-s
       Carbon::now()->endOfMonth()->format('Y-m-d'),
      Carbon::now()->startOfMonth()->format('Y-m-d')
        ];

$quantidadeMesPassado = Produto::where(['teste'=>$teste])
            //Caso for dateTime e precise usar somente datas no between passa um DB::raw("date_format(updated_at, '%Y-%m-%d')") dentro do whereBetween que ira fazer validações somente por data, mas irá funcionar de boa.
             ->whereBetween('updated_at',$datas)
             ->get()
             ->count();

Any questions send a comment here if I can help, it will be a pleasure.

  • In the algorithm presented by another answer helped to have a basis, but this answer helped to correct another error that gave. To put ->format('Y-m-d') on Carbon dates. Thank you very much for the help.

  • Remembering that you can exchange Now() for create($data) and get start of the month and end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.