Home > Net >  does Laravel have choices in model? like Django
does Laravel have choices in model? like Django

Time:08-05

I'm wondering does Laravel have something like Django choices in models?

for example in Django: Django document

class Card(models.Model):

    class Suit(models.IntegerChoices):
        DIAMOND = 1
        SPADE = 2
        HEART = 3
        CLUB = 4

    suit = models.IntegerField(choices=Suit.choices)

CodePudding user response:

Use Enums, a new Feature for PHP 8.1.

enum Suit:integer
{
    case DIAMOND = 1;
    case SPADE = 2;
    case HEART = 3;
    case CLUB = 4;
}

In your model.

class Card extend Model
{
    protected $casts = [
        'suit' => Suit::class,
    ];
}

Now when creating a card you can use the enum.

$card->fill(['suit' => Suit::DIAMOND]);

Or from input.

$card->fill(['suit' => Suit::from($request->get('suit'))]);

The documentation on Enums can be found here.

  • Related