1

I have a simply query like this:

$events = EventHistory::where('u_h_id', $id)
                      ->where('has_read', 0)
                      ->get(['event_type']);

This will return a result that looks like this:

[
{
event_type: 1
},
{
event_type: 2
},
{
event_type: 2
},
{
event_type: 4
},
{
event_type: 6
},
{
event_type: 1
},
{
event_type: 3
},
{
event_type: 1
},
{
event_type: 4
},
{
event_type: 1
},
{
event_type: 4
},
{
event_type: 4
}]

But now I need a way to count the specific values so I can return now many results exist in the different event types

eg, on the result above I want to return

$type1 = 4;
$type2 = 2;
$type3 = 1;
$type4 = 4;
$type6 = 1;

There are 4 results that has a event_type value of 1 etc..

Kiow
  • 870
  • 4
  • 18
  • 32
  • Do you want RDBMS server do it for you or you want to do it in PHP script (via collections). Also share table schema. – Kyslik Aug 02 '17 at 17:43
  • Possible duplicate of [Laravel Eloquent groupBy() AND also return count of each group](https://stackoverflow.com/questions/18533080/laravel-eloquent-groupby-and-also-return-count-of-each-group) – Kyslik Aug 02 '17 at 17:57

2 Answers2

2

Dummy way to do it is use foreach

$result = [];
foreach($events as $key => $value) {
    $result[$value['event_type']] = isset($result[$value['event_type']]) ? $result[$value['event_type']]+1 : 1;
}

// now you have indexed array $result with the desired output

http://sandbox.onlinephpfunctions.com/code/b49150f192b99b218708d5dd8037fe5a23457a79

Kyslik
  • 8,217
  • 5
  • 54
  • 87
1

Got it to work using this:

$events = EventHistory::where('u_h_id', $id)
    ->where('has_read', 0)
    ->select('event_type', \DB::raw('count(*) as count'))
    ->groupBy('event_type')
    ->get();
Kiow
  • 870
  • 4
  • 18
  • 32
  • Well of course, I linked you to the duplicate, I hope this gets closed, next time do search before asking. – Kyslik Aug 02 '17 at 19:46