PHP
Utilizing Attribute Casting for JSON and Arrays in Eloquent
Master Laravel Eloquent's attribute casting to automatically convert database JSON columns into PHP arrays or collections, simplifying data handling.
// In your Model (e.g., User.php)
class User extends Model
{
// Define columns that should be cast
protected $casts = [
'options' => 'array',
'settings' => 'json',
'preferences' => 'collection',
'tags' => 'array', // Another common use case for an array of strings
];
// 'options' column is stored as JSON string in DB, but accessed as PHP array
// 'settings' column is stored as JSON string in DB, but accessed as PHP object/array
// 'preferences' column is stored as JSON string in DB, but accessed as an Illuminate\Support\Collection
}
// Usage example
$user = User::find(1);
// Accessing 'options' as a PHP array
$user->options['theme'] = 'dark';
$user->options['notifications'] = true;
$user->save();
// Accessing 'settings' as a PHP object/array
$settings = $user->settings;
$settings->newsletter = true;
$user->settings = $settings;
$user->save();
// Accessing 'preferences' as a Collection
$user->preferences->push('new_item');
$user->save();
// Add new value to 'tags' array
$user->update(['tags' => array_merge($user->tags, ['new_tag'])]);
How it works: Attribute casting in Eloquent automatically converts attribute values to common data types when they are retrieved from or saved to the database. By defining the `$casts` property on your model, you can specify that a JSON column should be treated as a PHP `array`, `json` (which can be an array or object), or an `Illuminate\Support\Collection`, among other types. This streamlines working with structured data stored in a single database column, eliminating the need for manual `json_encode()` and `json_decode()` calls.