😞Thuộc tính $casts (ok)
https://viblo.asia/p/accessors-va-mutators-trong-laravel-55-bJzKmkEEl9N
PreviousLaravel 9 Eloquent Mutators and Accessors Example (ok)NextLaravel 9 Multiple Image Upload Tutorial
Last updated
https://viblo.asia/p/accessors-va-mutators-trong-laravel-55-bJzKmkEEl9N
Last updated
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'is_admin' => 'boolean',
];
}
$user = App\User::find(1);
if ($user->is_admin) {
//
}protected $casts = [
'status' => ProductStatusEnum::class
];<?php
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 array
*/
public function get($model, $key, $value, $attributes)
{
return json_decode($value, true);
}
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param array $value
* @param array $attributes
* @return string
*/
public function set($model, $key, $value, $attributes)
{
return json_encode($value);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Casts\Json;
class Product extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable = [
'name',
'price',
'status',
'is_available',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'options' => Json::class,
];
}