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

mcbates's avatar

How to make class available for the app() helper?

I'm following this tutorial to create class based model factories.

I'm struggling to register the custom class with the app() helper.

Here is the custom model factory class:

// database/LeagueFactory.php
<?php

use App\League;

class LeagueFactory
{
    public function create($overrides = [])
    {
        return factory(League::class)->create($overrides);
    }
}

And here's how I want to call it within a test:

$league = app(LeagueFactory::class)->create([
    'user_id' => $user->id,
    'season_id' => $season->id,
]);

I only get this error message: Illuminate\Contracts\Container\BindingResolutionException: Target class [StrikeFactory] does not exist

Where and how can I register the custom model factory, so I can globally access it?

0 likes
3 replies
fylzero's avatar

I'm going to take a wild guess that your LeagueFactory class is in your factory folder, not your app folder? Maybe?

Or the class isn't bound to the service container?

1 like
goldtaste's avatar

You will probably need to add a namespace to the LeagueFactory class. Is it in the app folder?

Then add

namespace App;

at the top of the file.

Also, have you tried creating the factory without the app helper in the tests. What happens if you do:

$league = (new LeagueFactory)->create([ 'user_id' => $user->id, 'season_id' => $season->id, ]);

May give you an error message that is easier to understand

mcbates's avatar
mcbates
OP
Best Answer
Level 4

Yes, @fylzero and @goldtaste, just referencing with a namespace solved this issue.

Just put my class file in app\FactoryClass and added namespace namespace App\FactoryClass and could import it easily with use App\FactoryClass\LeagueFactory and app(LeagueFactory::create()).

You might also use Realtime Facades to get rid of the app().

Please or to participate in this conversation.