Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

naspy971's avatar

How to mock calls of Laravel scopes for unit testing?

I'm using Laravel 12 along with Pest (using Mockery), and I have this method :

public function destroy(array $ids): array
    {
        $data= Item::findAllByFieldIn('id', $ids)->get();

       // other code...
    }

findAllByFieldIn is a scope method that comes from a trait used in Item model.

For my unit test, I need to mock findAllByFieldIn but I haven't found any working solution so far...

Is there a proper way to mock a method (scope in this case) of a model ? Thanks.

0 likes
4 replies
martinbean's avatar

@naspy971 This is a sign you need to either re-factor to something that is mockable, or that this isn’t a unit test at all.

Personally, I would just make this a feature test, seed the database with the items you want to delete, and check the expected records are deleted when you hit this endpoint.

Also, as an aside, your method is redundant as Eloquent’s find method already allows you to pass multiple IDs to find multiple records:

$items = Item::query()->find($ids);

Source: https://github.com/laravel/framework/blob/df826dfbb63e8894ea9915b2ba9ce06e407547b0/src/Illuminate/Database/Eloquent/Builder.php#L555-L569

Or, alternatively, you can use the more appropriate findMany method if that’s your actual intention:

$items = Item::query()->findMany($ids);
1 like
naspy971's avatar

Thanks for your reply.

I actually want to unit test the whole method as a unit test, but the method also contains thils call which i want to mock in order to bypass any database call and isolate the test from the environment.

Previously, i was using a repository, which was easily mockable, but i'm replacing the repository concept with Laravel scopes as scopes seems more as a best practice for Laravel than the repository pattern which is included by default in Symfony but not Laravel.

And for this specific method, i've put 'id' as example but it can use any field so it's not spcific to a search by id.

naspy971's avatar

Ok I get your points, and thanks for poiting that.

But my main concern is not the content of my scopes here, although I'll take a look on that, my main concern is the need to be able to mock static calls of models made inside methods which i want to unit test as a whole.

krisi_gjika's avatar

I think the problem is in your approach. You are trying to test a trait in isolation, that needs to boot a model and eloquent that in turn needs to boot the application. Normally anything involving the application container is not a unit test, but a feature test. I think if you made a feature test instead you would have much simpler time

Please or to participate in this conversation.