← Back to all snippets
PHP

Customizing Model Attribute Serialization with Eloquent Custom Casts

Define custom logic for how Eloquent serializes and deserializes complex model attributes to and from the database using custom casts for advanced data handling.

<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Collection;

// Example Value Object or complex data type
class TagsCollection extends Collection
{
    public function toString(): string
    {
        return $this->implode(',');
    }
}

class AsTagsCollection implements CastsAttributes
{
    public function get($model, string $key, $value, array $attributes)
    {
        return $value ? new TagsCollection(explode(',', $value)) : new TagsCollection();
    }

    public function set($model, string $key, $value, array $attributes)
    {
        if ($value instanceof TagsCollection) {
            return $value->toString();
        }
        if (is_array($value)) {
            return implode(',', $value);
        }
        return $value;
    }
}

// In your Model (e.g., app/Models/Article.php)
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Casts\AsTagsCollection;

class Article extends Model
{
    protected $casts = [
        'tags' => AsTagsCollection::class,
    ];

    protected $fillable = ['title', 'tags'];
}

// Example Usage:
$article = Article::create([
    'title' => 'My New Article',
    'tags' => ['laravel', 'php', 'eloquent']
]);

// Accessing the cast attribute
$tags = $article->tags; // $tags is an instance of TagsCollection
echo $tags->toString(); // laravel,php,eloquent

// Updating the cast attribute
$article->tags = new TagsCollection(['database', 'orm']);
$article->save();

// Or with an array, which the setter can handle
$article->tags = ['webdev', 'frontend'];
$article->save();
How it works: Custom casts allow you to define how Eloquent converts a model attribute's raw database value into a more complex PHP object (like a Value Object or a custom collection) and vice-versa. This snippet creates an `AsTagsCollection` custom cast to manage comma-separated tags stored as a string in the database, automatically converting them to a `TagsCollection` object when retrieved and back to a string when saved. This enhances type safety and encapsulates complex attribute logic within dedicated cast classes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs