In Laravel 11, you can use custom casting to achieve the desired behavior of casting an enum value to its name. You can create a custom cast class that handles the conversion. Here’s how you can do it:
- Create a Custom Cast Class:
First, create a custom cast class that will handle the conversion of the enum value to its name.
php artisan make:cast BookingTypeCast
Then, implement the CastsAttributes interface in the generated class:
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use App\Enums\BookingType;
class BookingTypeCast implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes)
{
return BookingType::toName($value);
}
public function set($model, string $key, $value, array $attributes)
{
return $value;
}
}
- Update Your Enum:
Ensure your enum has the toName method as you have already defined:
namespace App\Enums;
enum BookingType: int implements HasLabel
{
case Booking = 0;
case NotAvailable = 1;
case Subscription = 2;
public static function toName($value): string
{
return match ($value) {
self::Booking->value => 'Booking',
self::NotAvailable->value => 'NotAvailable',
self::Subscription->value => 'Subscription',
};
}
}
- Use the Custom Cast in Your Model:
Finally, use the custom cast in your model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Casts\BookingTypeCast;
class YourModel extends Model
{
protected $casts = [
'type' => BookingTypeCast::class,
];
}
With this setup, whenever you access the type attribute on your model, it will automatically be cast to the name of the enum value.
This approach keeps your code clean and leverages Laravel's custom casting feature to handle the conversion seamlessly.