#Eloquent: Cast specific Element from JSON row to Enum

5 messages · Page 1 of 1 (latest)

celest lintel
#

Good day, may I can't describe it exactly or good what I am looking for.

To avoid "magic numbers" in my code, I want to use a Enum that use Shorts from Names for the IDs (we talk about Class IDs from a game here).
The Enum looks like this:

<?php

enum Classes: int
{
  case ADV = 0;
}

(shorted it for readability)
Now I get the list of classes for a character (from a player) as JSON from SQL, usually I casted it to object, and would "continue" with this, but is there a way to use the data inside the JSON as object and for example cast the id to the enum? If I understood it right, it should be able for example then to do this:

foreach ($character->classes as $clas)
{
  if ($class->id === Classes::ADV) {
    // do something with it
  }
}

or isnt this possible (or may I missunderstood it).

Maybe helpful: if I remove protected $casts = ['classes' => 'object']; I retrive the classes as string, not object/array/json.
Hope it is understandable what I meant, if not o.o ask, I will try to help understand what I try

pliant kayak
#

AFAIK there isn't a way to cast a specific value from a json column to an enum.

Since this id value seems like an important enough piece of data for your model that you want to create an enum for it, I'd reccomend removing it from this json column and putting it into its own dedicated column.

In general its better to avoid using JSON columns unless absolutely necessary because these kinds of restrictions exist

polar bane
celest lintel
celest lintel