Filtering Collection Objects by Type with whereInstanceOf

Laravel's whereInstanceOf method provides a clean way to filter collections based on object types, particularly useful when dealing with polymorphic relationships or mixed object collections.

Filtering Collection Objects by Type with whereInstanceOf

ARE YOU TIRED OF LOW SALES TODAY?

Connect to more customers on doacWeb

Post your business here..... from NGN1,000

WhatsApp: 09031633831

ARE YOU TIRED OF LOW SALES TODAY?

Connect to more customers on doacWeb

Post your business here..... from NGN1,000

WhatsApp: 09031633831

ARE YOU TIRED OF LOW SALES TODAY?

Connect to more customers on doacWeb

Post your business here..... from NGN1,000

WhatsApp: 09031633831

Filtering Collection Objects by Type with whereInstanceOf

Laravel's whereInstanceOf method provides a clean way to filter collections based on object types, particularly useful when dealing with polymorphic relationships or mixed object collections.

 'John']),
    new Post(['title' => 'Hello']),
    new User(['name' => 'Jane']),
]);
$users = $collection->whereInstanceOf(User::class);

Let's explore a practical example of handling a notification feed with different types of activities:

comments()->latest()->limit(5)->get(),
            ...$user->likes()->latest()->limit(5)->get(),
            ...$user->follows()->latest()->limit(5)->get(),
        ]);
        // Sort all activities by created_at
        $activities = $activities->sortByDesc('created_at');

        return [
            'comments' => $activities->whereInstanceOf(Comment::class)
                ->map(fn (Comment $comment) => [
                    'type' => 'comment',
                    'text' => $comment->body,
                    'post_id' => $comment->post_id,
                    'created_at' => $comment->created_at
                ]),
            'likes' => $activities->whereInstanceOf(Like::class)
                ->map(fn (Like $like) => [
                    'type' => 'like',
                    'post_id' => $like->post_id,
                    'created_at' => $like->created_at
                ]),
            'follows' => $activities->whereInstanceOf(Follow::class)
                ->map(fn (Follow $follow) => [
                    'type' => 'follow',
                    'followed_user_id' => $follow->followed_id,
                    'created_at' => $follow->created_at
                ])
        ];
    }
}

WhereInstanceOf simplifies type-based filtering in collections, making it easier to handle mixed object types while maintaining clean, readable code.


The post Filtering Collection Objects by Type with whereInstanceOf appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow