Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Filtering Collection Objects by Type with whereInstanceOf

Last updated on by

Filtering Collection Objects by Type with whereInstanceOf image

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.

<?php
 
use App\Models\User;
use App\Models\Post;
use App\Models\Comment;
use Illuminate\Support\Collection;
 
$collection = collect([
new User(['name' => '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:

<?php
 
namespace App\Services;
 
use App\Models\Comment;
use App\Models\Like;
use App\Models\Follow;
use Illuminate\Support\Collection;
 
class ActivityFeedService
{
public function getUserFeed(User $user): array
{
// Get all activities
$activities = collect([
...$user->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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell

The latest

View all →
Laravel Idempotency: HTTP Idempotency Middleware for Laravel image

Laravel Idempotency: HTTP Idempotency Middleware for Laravel

Read article
Polyscope for Windows is Now Available image

Polyscope for Windows is Now Available

Read article
Laravel Sluggable image

Laravel Sluggable

Read article
Ship AI with Laravel: RAG with Embeddings and pgvector in Laravel 13 image

Ship AI with Laravel: RAG with Embeddings and pgvector in Laravel 13

Read article
Laravel Mobile Pass: Generate Apple Wallet and Google Wallet Passes image

Laravel Mobile Pass: Generate Apple Wallet and Google Wallet Passes

Read article
PHPverse 2026 Returns June 9th image

PHPverse 2026 Returns June 9th

Read article