Skip to content

Instantly share code, notes, and snippets.

@blood72
Created October 7, 2020 04:35
Show Gist options
  • Save blood72/962a9148dd3b8bd1cb7c8e5cbe877399 to your computer and use it in GitHub Desktop.
Save blood72/962a9148dd3b8bd1cb7c8e5cbe877399 to your computer and use it in GitHub Desktop.
Load Eloquent directly from DB stored in json format snapshot data.
<?php
namespace App\Models;
class Example extends Model
{
/**
* @see Post
* @param string $value
* @return Post|\Illuminate\Database\Eloquent\Model
*/
public function getPostAttribute($value)
{
return $this->hydrateModelFromJson(Post::class, $value);
}
}
<?php
namespace App\Models;
abstract class Model extends \Illuminate\Database\Eloquent\Model
{
protected function hydrateModelFromJson(string $model, $value)
{
return $model::hydrate([$this->fromJson($value)])->first();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment