Filter attribute on collection
I'm trying filtering an attribute on a collection of eloquent. I have done in 2 ways, both working.
$bookings = Booking::all()->whereIn('attributes.status', [Booking::NEW_BOOKING, Booking::CONFIRMED]);
$bookings = Booking::all()->filter(function ($booking) {
return in_array($booking->status, [Booking::NEW_BOOKING, Booking::CONFIRMED]);
});
I know there is another way like:
Booking::where('status', Booking::NEW_BOOKING)->get();
But I still want to know which way you prefer an why ?
I'd appreciate any opions. Thanks.
Let your database do the work. You're doing extra work by grabbing everything and then filtering after the fact when you don't need to.
// My vote
Booking::where('status', Booking::NEW_BOOKING)->get();
Booking::whereIn('status', [Booking::NEW_BOOKING, Booking::CONFIRMED])->get();
I'd also go one step further and make a custom query scope that allows you to do this:
Booking::status(Booking::NEW_BOOKING)->get();
Booking::status([Booking::NEW_BOOKING, Booking::CONFIRMED])->get();
Actually, I define a relationship in Event class:
class Event extends Model {
public function bookings()
{
return $this->hasMany('App\Booking', 'event_id');
}
}
I just want to grab some new bookings:
public function newBookings {
$booking = $this->bookings>whereIn('attributes.status', [Booking::NEW_BOOKING, Booking::CONFIRMED]);
}
Do you have another suggestion ?
Please or to participate in this conversation.