Created
January 30, 2024 16:05
-
-
Save MrPunyapal/957f1cbbe3910619200668585caaf9e4 to your computer and use it in GitHub Desktop.
Laravel Eloquent Model Tip for Enum Handling with $casts and Array Columns π
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use App\Enums\PostStatus; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Database\Eloquent\Attributes\Attribute; | |
class Post extends Model | |
{ | |
// We can easily cast the 'status' column to an enum instance | |
// since it is a string column that contains the enum value | |
protected $casts = [ | |
'status' => PostStatus::class, | |
]; | |
// However, for cases where the enum value is within an array or JSON column, | |
// a custom cast or attribute casting is needed: | |
public function options(): Attribute | |
{ | |
return Attribute::make( | |
// The 'get' method is called when the attribute is retrieved from the model | |
get: function ($options) { | |
// Decode the JSON string to an array | |
$options = json_decode($options, true); | |
// Cast the 'status' key to an enum instance | |
// as it is a string key that contains the enum value | |
$options['status'] = PostStatus::from($options['status']); | |
return $options; | |
}, | |
// The 'set' method is called when the attribute is set on the model | |
set: function ($options) { | |
// Check if the 'status' key is an instance of PostStatus | |
$options['status'] = $options['status'] instanceof PostStatus | |
// If it is, get the value of the enum instance | |
? $options['status']->value | |
// If it is not, keep it as is. | |
// You can also validate if it exists in the enum. | |
: $options['status']; | |
// Then encode the options to JSON | |
return json_encode($options); | |
} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment