Kiow
Kiow

Reputation: 880

Laravel Count result based on specific value

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..

Upvotes: 1

Views: 1926

Answers (2)

Kiow
Kiow

Reputation: 880

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();

Upvotes: 1

Kyslik
Kyslik

Reputation: 8385

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

Upvotes: 2

Related Questions