Mutators & Casting
Laravel Eloquent ORM Mutators & Casting
Categories:
Set Default Value
class Post extends Model
{
$attributes = [
'meta' => '[]',
'is_published' => true,
];
$casts = [
'meta' => 'array',
'is_published' => 'boolean',
];
}
Attribute Casting
The supported cast types
array
AsStringable::class
boolean
collection
date
datetime
immutable_date
immutable_datetime
decimal:<precision>
double
encrypted
encrypted:array
encrypted:collection
encrypted:object
float
integer
object
real
string
timestamp
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'is_admin' => 'boolean',
];
}
Array & JSON Casting
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\AsArrayObject;
class User extends Model
{
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'options' => 'array',
'array_options' => AsArrayObject::class,
'collection_options' => AsCollection::class,,
];
}
Select & Update from database
use App\Models\User;
$user = User::find(1);
$options = $user->options;
$options['key'] = 'value';
$user->options = $options;
$user->save();
Update from the eloquent update method
$user = User::find(1);
$user->update(['options->key' => 'value']);
Event funcion
vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php
Event function name | Description |
---|---|
retrieved($callback) | Register a retrieved model event |
saving($callback) | Register a saving model event |
saved($callback) | Register a saved model event |
updating($callback) | Register an updating model event |
updated($callback) | Register an updated model event |
creating($callback) | Register a creating model event |
created($callback) | Register a created model event |
replicating($callback) | Register a replicating model event |
deleting($callback) | Register a deleting model event |
deleted($callback) | Register a deleted model event |
static::creating()
Before booting
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
// auto-sets values on creation
static::creating(function ($query) {
$query->is_voicemail = $query->is_voicemail ?? true;
});
}
}
After booted
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::created(function ($user) {
//
});
}
}