Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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
You can’t perform that action at this time.