Home >Backend Development >PHP Tutorial >Filtering Collection Objects by Type with whereInstanceOf

Filtering Collection Objects by Type with whereInstanceOf

Karen Carpenter
Karen CarpenterOriginal
2025-03-06 02:02:08315browse

Filtering Collection Objects by Type with whereInstanceOf

Laravel's whereInstanceOf method provides a concise way to filter sets based on object type, which is especially useful when dealing with polymorphic relationships or mixed object sets.

The following is a simple example showing how to filter a collection of whereInstanceOf and User objects using Post:

<?php
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);

Let's look at a more practical example: handling notification feeds containing 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
    {
        // 获取所有活动
        $activities = collect([
            ...$user->comments()->latest()->limit(5)->get(),
            ...$user->likes()->latest()->limit(5)->get(),
            ...$user->follows()->latest()->limit(5)->get(),
        ]);
        // 按创建时间排序
        $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
                ])
        ];
    }
}

whereInstanceOfSimplifies type-based filtering in collections, making it easier to handle mixed object types while keeping the code simple and easy to read.

The above is the detailed content of Filtering Collection Objects by Type with whereInstanceOf. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn