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

hrawat0308's avatar

cannot declare class because name already in use

I was working on twitter clone(in laravel from scratch series) on laravel 8, i ran command in tinker i.e App\Models\Tweets::factory()->make();

is says error .i.e:

Symfony\Component\ErrorHandler\Error\FatalError

Cannot declare class Database\Factories\TweetsFactory, because the name is already in use

at C:\wamp64\www\tweety\database\factories\TweetsFactory.php:9 5▕ use App\Models\Tweet; 6▕ use Illuminate\Database\Eloquent\Factories\Factory; 7▕ use Illuminate\Support\Str; 8▕ ➜ 9▕ class TweetFactory extends Factory 10▕ { 11▕ /** 12▕ * The name of the factory's corresponding model. 13▕ *

1 C:\wamp64\www\tweety\vendor\filp\whoops\src\Whoops\Run.php:408 Whoops\Run::handleError("Cannot declare class Database\Factories\TweetFactory, because the name is already in use", "C:\wamp64\www\tweety\database\factories\TweetFactory.php")

2 [internal]:0 Whoops\Run::handleShutdown()

0 likes
8 replies
SarwarAhmed's avatar

In Laravel 8

App\Models\Model::factory()->make();

App\Models\Tweet::factory()->make();
hrawat0308's avatar

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model;

class Tweets extends Model { use HasFactory; }

netr's avatar

Yeah. I'm getting the same issue using PHPStorm.

My individual tests run perfectly fine, but when I run the whole file I get this error.

Using the laravel/legacy-factories composer package and using the old factory style works for now.

Ap3twe's avatar

Did you delete a file created before, make sure you check the namespace correctly. Or you can clear cache and config files. php artisan cache:clear and php artisan config:clear after you can use composer autodump

LyonelZ's avatar

I am having the same issue.

I have 2 tests running on the same file,

In the first test I run "data = Application::factory()->make()->toArray();" and the test passes.

The second test I run the same line of code "data = Application::factory()->make()->toArray();" I then get the error " Cannot declare class Database\Factories\ApplicationFactory, because the name is already in use"

vladitot's avatar

You should use only one way. Class-based factories, or legacy way. Your error is because legacy package use preloading whole folder with factories. Than, when you try to use some of new factories via class-based way, autoloader tries to open file once more. PHP knows nothing about "how much times you try to open file with class", it just tries to execute em. So, this way you have problem, that class-based factories opens 2 times and second time is trying to redeclare class. So error is in that.

You should choose: re-write all factories to new way and remove legacy package laravel/legacy-factories or use only old way.

3 likes

Please or to participate in this conversation.