Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shankhadevpadam/027523bdfbf230d775fb92a3ee52e0b2 to your computer and use it in GitHub Desktop.
Save shankhadevpadam/027523bdfbf230d775fb92a3ee52e0b2 to your computer and use it in GitHub Desktop.
<?php
namespace App\Traits;
use App\Meta;
trait HasMeta
{
public function fromMeta($key)
{
return optional($this->meta->where('key', $key)->first())->value;
}
public function meta()
{
return $this->morphMany(Meta::class, 'metable');
}
public function updateMeta($values)
{
$metas = $this->meta;
collect($values)->filter()->each(function ($value, $key) use ($metas) {
$meta = $metas->where('key', $key)->first();
if ($meta) {
$meta->value = $value;
$meta->save();
return;
}
$meta = new Meta();
$meta->forceFill(compact(['key', 'value']));
$this->meta()->save($meta);
});
}
}
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMetasTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('metas', function (Blueprint $table) {
$table->increments('id');
$table->integer('metable_id');
$table->string('metable_type');
$table->string('key');
$table->longText('value');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('metas');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment