PHP
Cast Eloquent Attributes to Custom Types
Automatically convert model attributes to specific data types like arrays, collections, booleans, dates, or custom cast classes using Eloquent casting for easier handling.
// app/Models/Product.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Casts\Json; // Assume you have a custom cast class
class Product extends Model
{
use HasFactory;
protected $fillable = ['name', 'price', 'is_published', 'options', 'release_date', 'details'];
protected $casts = [
'is_published' => 'boolean',
'options' => 'array', // Will automatically convert JSON string to PHP array
'release_date' => 'date', // Will return a Carbon instance
'details' => 'collection', // Will return an Illuminate\Support\Collection instance
'status_history' => Json::class, // Custom cast example
];
// Example Usage
// $product = Product::find(1);
// var_dump($product->is_published); // boolean true/false
// echo $product->release_date->format('Y-m-d'); // Carbon instance methods
// print_r($product->options['color']); // Access array elements
// print_r($product->details->toArray()); // Access collection methods
// $product->options = ['size' => 'L', 'color' => 'blue']; // Stored as JSON
// $product->is_published = true; // Stored as 1/0
// $product->save();
}
// app/Casts/Json.php (Example Custom Cast Class)
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class Json implements CastsAttributes
{
public function get($model, string $key, mixed $value, array $attributes): mixed
{
return json_decode($value, true);
}
public function set($model, string $key, mixed $value, array $attributes): mixed
{
return json_encode($value);
}
}
How it works: Eloquent attribute casting provides a convenient way to convert model attributes to common data types (like boolean, array, collection, date) or even custom types when retrieving or setting them. By defining the `$casts` property in your model, Laravel automatically handles the serialization and deserialization, ensuring attributes are always returned in the desired format, simplifying data manipulation within your application.