Home > Back-end >  Laravel 9 enum conditional if
Laravel 9 enum conditional if

Time:06-03

I'm create one enum, and I added one condition:

<?php

declare(strict_types=1);

namespace App\Enums;

use App\Models\collections;

enum ServiceColections : string {


    case POS = (isset(collections::first()))? 'POS' : '';

}

the condition is the following if there are items in the database(table collections), so create case POS, but if they don't exist don't create.

currently I'm having this error: Enum case value must be compile-time evaluatable

why it dont work?

CodePudding user response:

As the error its self say, this will not work at the time of compiling.

What we can do is, add enum method:

use App\Models\collections;

enum ServiceColections 
{
    case POS;

    public function collection(): string // name the function of your choice
    {
        return match($this) 
        {
            self::POS => collections::first() ? 'POS' : '',
        };
    }
}

Methods can be used like so:

\App\Enums\ServiceColections::POS->collection();
  • Related