Skip to content

Instantly share code, notes, and snippets.

@ikristher
Last active April 19, 2023 21:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikristher/4b8b1ea0450b196bc2d9569b2b3a6ff2 to your computer and use it in GitHub Desktop.
Save ikristher/4b8b1ea0450b196bc2d9569b2b3a6ff2 to your computer and use it in GitHub Desktop.
Polymorphic Metadata Relationships in Laravel
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMetaDatasTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('metadata', function (Blueprint $table) {
$table->increments('id');
$table->string('key');
$table->text('value')->nullable();
$table->integer('metable_id')->unsigned();
$table->string('metable_type');
$table->timestamps();
$table->unique(['key','metable_id','metable_type']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('metadata');
}
}
trait CanHaveMetadata
{
/**
* Get All Metadata using Polymorphic Relationship
* @return mixed
*/
public function metadata()
{
return $this->morphMany(MetaData::class, 'metable');
}
/**
* Check if a metadata key already exist.
* @param $key
* @return bool
*/
public function hasMetadata($key)
{
return (boolean) $this->metadata()->whereKey($key)->count();
}
/**
* Retrieve a metadata of a Metadata.
* @param $key
* @return mixed
*/
public function getMetadata($key)
{
return $this->metadata()->whereKey($key)->first()->value;
}
/**
* Save or update metadata of a Model.
* @param $key
* @param $value
* @return mixed
*/
public function saveMetadata($key, $value)
{
$metadata = $this->metadata()->whereKey($key)->first() ?: new MetaData(['key' => $key]);
$metadata->value = $value;
return $this->metadata()->save($metadata);
}
}
use Illuminate\Database\Eloquent\Model;
class MetaData extends Model
{
//
protected $table = 'metadata';
protected $fillable = ['key','value'];
public function metable()
{
return $this->morphTo();
}
public function setValueAttribute($value)
{
if(is_array($value)){
$this->attributes['value'] = json_encode($value);
return ;
}
$this->attributes['value'] = $value;
}
public function getValueAttribute($value)
{
$decodeValue = json_decode($value,true);
if(is_array($decodeValue)){
return $decodeValue;
}
return $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment