Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

CharlesK's avatar

Laravel get month name by query

Imagine today's date is 6/15/2019

I'm trying to query my visitor with in this year of 2019 only.

Then, I want to know how many are on

1,2,3,4,5,6

I've tried

$raw = Visitor::query()
->whereYear('created_at', now()->year -1)
->get()
->pluck('created_at');

$data = [];
foreach ($raw as $i=>$date) {
    $data[$i] = Carbon::parse($date)->format('m');
    if(  Carbon::parse($date)->format('m')[0] != 0 ){
        $data[$i] = Carbon::parse($date)->format('m');
    }else{
        $data[$i] = str_replace('0','',Carbon::parse($date)->format('m'));
    }
}

// dd($data);

$dataValues = array_count_values($data);

dd($dataValues);

How to achieve that?

0 likes
7 replies
CharlesK's avatar

@tisuchi this is what I am getting now-

array:7 [▼
  6 => 714
  7 => 811
  8 => 314
  9 => 916
  10 => 764
  11 => 827
  12 => 765
]

Why would I get anything in the future since this month is only June (6) ?

2 likes
tisuchi's avatar

@charlesk

So, what you are expecting now? Do you expect the whole month list?

4 likes
CharlesK's avatar

@tisuchi I am expecting something like this-

array:9 [▼
      0 => 314
      1 => 916
      2 => 764
      3 => 827
      4 => 165
      5 => 225
      6 => 565
    ]

Meaning show all the previous months in this year.

1 like
tisuchi's avatar
tisuchi
Best Answer
Level 70

@charlesk

Try this-

Visitor::whereYear('created_at', Carbon::now()->year)
->select(DB::raw("MONTH(created_at) month"),DB::raw("count('month') as vistors_count"))
       ->groupby('month')
       ->get();
3 likes
CharlesK's avatar

thank you man. really appreciated your time.

3 likes

Please or to participate in this conversation.