Member-only story
How to Filter Laravel Collections Object by Type Using whereInstanceOf
Laravel’s whereInstanceOf
method offers a powerful, clean solution for filtering collections by object type. This functionality is particularly valuable when dealing with polymorphic relationships or collections containing mixed object types. By leveraging whereInstanceOf
, you can simplify complex type filtering while keeping your codebase maintainable and easy to read.
Basic Example: Filtering Mixed Object Collections
Consider a collection that contains multiple types of objects. Using whereInstanceOf
, you can filter out only the objects of a specific type:
use App\Models\User;
use App\Models\Post;
use Illuminate\Support\Collection;
$collection = collect([ new User(['name' => 'John']),
new Post(['title' => 'Hello']),
new User(['name' => 'Jane']),
]);
$users = $collection->whereInstanceOf(User::class);
// Result: Only User objects
This concise approach eliminates the need for manual type-checking, improving both performance and readability.
Real-World Use Case: Activity Feed Filtering
To demonstrate the true power of whereInstanceOf
, let’s build an activity feed service that aggregates different types of…