Mircha Emanuel D'Angelo

Customizing Data Transformations with Laravel CastsAttribute

Mircha Emanuel D'Angelo

In Laravel, custom casts allow for tailored data transformations, extending built-in casting capabilities. This is especially useful for handling complex data types or incorporating custom business logic directly into your models.

Laravel provides the CastsAttributes interface, which defines two key methods:
get: Transforms data when retrieved from the database.
set: Transforms data before it is stored in the database.

Below is an example of creating a custom cast for handling arrays stored as comma-separated values in the database.

Implementing a Custom Cast: CommaSeparatedArray

Suppose we want to store a list of tags as a comma-separated string in the database, but work with it as an array in our application.

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;

class CommaSeparatedArray implements CastsAttributes
{
    public function get(Model $model, string $key, mixed $value, array $attributes): array
    {
        return explode(',', $value);
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): string
    {
        // Converts the array into a comma-separated string
        return implode(',', $value);
    }
}

Using It in a Model

You can register the custom cast in the $casts array of your model to seamlessly handle the transformation:

namespace App\Models;

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

class Post extends Model
{
    protected $casts = [
        'tags' => CommaSeparatedArray::class,
    ];
}

Example Usage

Here’s how you can use the tags attribute in your application:

$post = new Post();

// Saving an array of tags
$post->tags = ['laravel', 'php', 'development'];
$post->save();

// Retrieving the tags as an array
print_r($post->tags); 
// Output: ['laravel', 'php', 'development']

In the database, the tags attribute is stored as a string like laravel,php,development, while your application interacts with it as an array.

This approach simplifies the handling of structured data while maintaining a clean and efficient database schema.