Laravel 11 Using Custom Casts for Eloquent Models - Step by StepGuide

Laravel 11 Using Custom Casts for Eloquent Models - Step by StepGuide

Custom casts in Laravel helps you to transform the attributes whey they are accessed or stored in DB. They help us by maintaining our attributes in a consistent format .Custom casts are particularly useful when dealing with JSON data, encrypted fields, or any non-primitive data types.

To define a custom cast, you first create a class that implements the  CastsAttributes interface.

Step-by-Step Guide to Creating and Using Custom Casts

Create a Custom Cast Class

The first step in creating a custom cast is to define a class that implements the CastsAttributes interface. This interface requires two methods :  get and set.

namespace App\Casts; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; class Json implements CastsAttributes { /** * Cast the given value. * * @param \Illuminate\Database\Eloquent\Model $model * @param string $key * @param mixed $value * @param array $attributes * @return mixed */ public function get($model, string $key, $value, array $attributes) { return json_decode($value, true); } /** * Prepare the given value for storage. * * @param \Illuminate\Database\Eloquent\Model $model * @param string $key * @param mixed $value * @param array $attributes * @return mixed */ public function set($model, string $key, $value, array $attributes) { return json_encode($value); } }

The get method is responsible for transforming the raw value from the database into a format that your application can work with.

The  set method  is used to prepare the attribute for storage in the database. This method typically involves converting the attribute to a format that can be stored in the database.

Register the Custom Cast in Model

Once the custom cast class is created, you need to register it in your Eloquent model by adding it to the $castsproperty.

class User extends Authenticatable { use HasFactory, Notifiable; /** * Get the attributes that should be cast. * * @return array */ protected function casts(): array { return [ 'password' => 'hashed', 'settings' => Json::class, ]; } }

By adding  'settings' => Json::class  to the $casts property, Laravel will automatically use the Json cast class to transform the settings attribute whenever it is accessed or modified.

public function index() { $user = User::find(1); $user->settings = ['theme' => 'dark', 'notifications' => true]; $user->save(); // Accessing the attribute $settings = $user->settings; // ['theme' => 'dark', 'notifications' => true] }

When you set the settings attribute, the set method of the Json cast class is called, encoding the array to JSON before storing it in the database. When you access the settings attribute, the get method is called, decoding the JSON back to an array.

Advanced Custom Casts

Custom casts are not limited to simple transformations. You can perform more complex logic as needed.

For example, you might want to encrypt sensitive data before storing it and decrypt it when retrieving it.

namespace App\Casts; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Support\Facades\Crypt; class Encrypted implements CastsAttributes { public function get($model, string $key, $value, array $attributes) { return Crypt::decryptString($value); } public function set($model, string $key, $value, array $attributes) { return Crypt::encryptString($value); } }

Register the cast in model:

class User extends Authenticatable { use HasFactory, Notifiable; /** * Get the attributes that should be cast. * * @return array */ protected function casts(): array { return [ 'secret' => Encrypted::class, ]; } }

Now, whenever you set the secret attribute, it will be encrypted before storage, and decrypted when accessed.

Combining Multiple Casts

You can also combine multiple custom casts within a single model. This allows you to handle different attributes in different ways.

protected function casts(): array { return [ 'settings' => Json::class, 'secret' => Encrypted::class, ]; }
Tags
Laravel Casts Laravel 11 Laravel Cusomt Casts Use Laravel Custom Casts Casts In Laravel Eloquent Casts Json Cast