😞Thuộc tính $casts (ok)
https://viblo.asia/p/accessors-va-mutators-trong-laravel-55-bJzKmkEEl9N
Thuộc tính $casts
cung cấp một phương thức tiện lợi về việc chuyển đổi các các thuộc tính sang các kiểu dữ liệu bình thường. Thuộc tính $casts
nên là một mảng có key là tên của các attribute được cast và giá trị là kiểu dữ liệu bạn muốn cast. Các kiểu dữ liệu để cast được hỗ trợ bao gồm: integer
, real
, float
, double
, string
, boolean
, object
, array
, collection
, date
, datetime
, và timestamp
. VD: cast thuộc tính is_admin từ kiểu integer sang boolean:
he supported cast types are :
array
AsStringable::class
boolean
collection
date
datetime
immutable_date
immutable_datetime
decimal:<digits>
double
encrypted
encrypted:array
encrypted:collection
encrypted:object
float
integer
object
real
string
timestamp
<?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',
];
}
Giờ đây, thuộc tính is_admin
sẽ luôn luôn được cast thành kiểu boolean
khi bạn truy cập đến nó, thậm chí nếu giá trị của nó được lưu trong database là kiểu integer
:
$user = App\User::find(1);
if ($user->is_admin) {
//
}
Chú ý: ngoài cách kiểu thuộc tính ở trên ta có các kiểu khai báo riêng ví dụ như
protected $casts = [
'status' => ProductStatusEnum::class
];
Đọc thêm ví dụ ở dưới: https://c-i-ph-n-m-m-tr-n-ubuntu-c-n-thi.gitbook.io/project/tim-hieu-va-su-dung-enum-trong-larave-full-ok
Hoặc viết file riêng
C:\xampp8\htdocs\plugindev\app\Casts\Json.php
<?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);
}
}
C:\xampp8\htdocs\plugindev\app\Models\Product.php
<?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,
];
}
Last updated
Was this helpful?