Home > Net >  How to fix class not found error for namespaced Enums?
How to fix class not found error for namespaced Enums?

Time:03-10

I have an enums folder created manually in the root directory of a Laravel project. Currently, there is only one file called TransactionTypes and I want to use it in my migration (in another file too in the future). However, when I test the app, it throws an error.

Class "Enums\TransactionTypes" not found

My migration that uses this enum look like this

<?php

use App\Models\Foodstuff;
use Enums\TransactionTypes;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(Foodstuff::class);
            $table->enum('type', TransactionTypes::cases()); // HERE
            $table->unsignedInteger('stock');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('transactions');
    }
};

I have already declared a namespace in my enum

<?php

namespace Enums;

enum TransactionTypes
{
    case in;
    case out;
    case cancelled;
    case returned;
}

I tried to execute sail composer dump-autoload but it still doesn't work. How can I fix it?

CodePudding user response:

It is good practice to have enums folder inside app folder maybe change it to

app/Enums/TransactionTypes.php

Second, i recommend some changes in the enum class:

  • Change namespace to App\Enums
  • Add return type
  • Add values to cases
<?php

namespace App\Enums;

enum TransactionTypes: string
{
    case in = "in";
    case out = "out";
    case cancelled = "cancelled";
    case returned = "returned";
}

Third, run sail composer dump-autoload

  • Related