Eloquent uses casts to process data # Overview
Many times you want to use json to store data. using $ casts is the best option, but you can do more.
Basic
Here is the official document, link.
There is also a RryTip video about casts, Use casts change your datetype
Deepen
Then, let's further process this data relationship.
Here is an example of a user image (avatar). we need to store the uploaded original image (original) and the processed small image (thumbnail ), you can think of this as a one-to-one relational model. Naturally, we have the Avatar class.
Demo
For simplicity, modify create_users_table
$table->increments('id');$table->string('name');$table->json('avatar')->nullable();$table->timestamps();
Then define it in User. php.
protected $fillable = [ 'name', 'avatar'];protected $casts = [ 'avatar' => 'json'];
Now we have a simple definition, but we have not entered the next one. but first test routes. php.
Route::get('/', function() { User::create([ 'name' => 'RryLee', 'avatar' => [ 'original' => 'original-avatar.jpg', 'thumbnail' => 'original-avatar.thumbnail.jpg', ] ]);});Route::get('/get', function() { $user = User::findOrFail(1); return $user;});
You don't need to check whether the data can be stored or obtained.
The problem arises.
How do you modify it now (here we only assume that the user has re-cropped the source image, but it only indicates the modification). at this time, we still need to introduce our Avatar class.
avatar = $avatar; $this->user = $user; } public function get($key) { return array_get($this->avatar, $key); } public function set($key, $value) { $this->avatar[$key] = $value; return $this->persist(); } public function has($key) { return array_key_exists($key, $this->avatar); } public function all() { return $this->avatar; } public function merge(array $attributes) { $this->avatar = array_merge( $this->avatar, array_only($attributes, static::$allowed) ); return $this->persist(); } protected function persist() { return $this->user->update([ 'avatar' => $this->avatar ]); } public function __get($key) { if ($this->has($key)) { return $this->get($key); } throw new Exception("The {$key} avatar not exists."); }}
Here I directly used a piece of code, note persist ()
Then, add the link to the User model just like adding a link.
public function avatar() { return new Avatar(isset($this->avatar) ? $this->avatar : [], $this);}
Now we can operate our avatar as much as possible.
Route::get('save', function() { $user = User::findOrFail(1); $avatar = $user->avatar(); $avatar->set('original', 'change.jpg'); return 'Done!';});
The value in the database should change!
Summary
Eloquent really improves efficiency, simplicity, and variety of changes!