Tuesday, January 2, 2024

Laravel artisan migrate PHP Fatal error: Cannot declare class, because the name is already in use : Solution

When I was trying to migrate a database in Laravel Project using the 'php artisan migrate', I get the below error:

php artisan migrate

Migration table created successfully.

PHP Fatal error:  Cannot declare class CreatePasswordResetsTable, because the name is already in use in F:\Projects\database\migrations\2023_11_28_102415_create_password_resets_table.php on line 7    7

[Symfony\Component\Debug\Exception\FatalErrorException]

Cannot declare class CreatePasswordResetsTable, because the name is already in use


In such error, we can check below solutions:

First Solution :

It seems like you have 2 migrations done at different time with essentially same name.
for example : 2019_01_18_020910_create_Password_Reset_table.php
and 2019_01_16_020910_create_Password_Reset_table.php
Laravel will convert this filename eliminating the date signature and Camel Casing the remaining text.
So both of these migration will have class CreatePasswordResetsTableeven if the time signatures are different. Check if your migrations directory have such 2 files.
To check this run this from terminal in project root : 
grep -ri 'CreatePasswordResetsTable' database/migrations
You can delete one of the old migration file with the same table name. And run 'php artisan migrate'. It should work.
Second Solution :
Sometimes composer's internal class autoloading causes this issue. Do following to check if it resolves :
run composer install
Third Solution :
This is likely to be invalid but a same file should not have same class declaration 2 files by mistake.
Fourth Solution :
There might be a package you have installed which has a migration with same class name. To find run grep -ril'CreatePasswordResetsTable ' Vendor

If it shows any file then that's what causing 2 classes to have same names.

You can create a new one php artisan make:migration create_password_reset_table_custom and then copy what you have in current migration to the new one and delete the existing one(not from package but the one you have created).

This will create a class CreatePasswordResetsTable which is different than what the package already has.


One of the above solution will solve the issue

No comments: