Lijesh Shakya
Lijesh Shakya

Reputation: 2540

Laravel: Add Where Clause To Appended Custom Attribute

I have added a custom attribute age (in months) like:

//Casted so that I can use Carbon instance

protected $dates = ['date_of_birth'];

//Returns age in month

public function getAgeAttribute(){
    if(empty($this->date_of_birth){
        return null;
    }
    return $this->date_of_birth->diffInMonths();
}

I then appended age so that I can globally use age like:

protected $appends = ['age'];

I now need to use the age month on generating report which displays based on the age month:

How can I filter based on age in the collection of users?

//General Setup

$ages = [10, 20, 30, ...];

$users = User::get();

$requiredDetail = [];

Attempt 1

I tried to use where clause but is not working

foreach($ages as $age){
    $requiredDetail[$age] = $users->where('age', $age)->count();
} 

Attempt 2

I tried to use collection filter but is not working

foreach($ages as $age){
    $requiredDetail[$age] = $users->filter(function($user) use ($age){
        return $user->age == $age;
    });
}

The question is how can I filter casted age after retrieving it from the collection?

Upvotes: 1

Views: 1066

Answers (2)

VIKAS KATARIYA
VIKAS KATARIYA

Reputation: 6005

use WhereIn

$requiredDetail = $users->whereIn('age', $age)->count();

Upvotes: 1

mrhn
mrhn

Reputation: 18926

Use the Collection method whereIn().

$usersCertainAge = $users->whereIn('age', $ages);

Upvotes: 1

Related Questions