PHP code example of dhcmega / laravel-meta

1. Go to this page and download the library: Download dhcmega/laravel-meta library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dhcmega / laravel-meta example snippets


/**
* Run the migrations.
*
* @return void
*/
public function up()
{
    Schema::create('posts_meta', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('post_id')->unsigned()->index();
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

        $table->string('type')->default('null');

        $table->string('key')->index();
        $table->text('value')->nullable();

        $table->timestamps();
    });
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
    Schema::drop('posts_meta');
}

use Dhcmega\Metable\Metable;

class Post extends Eloquent
{
    use Metable;
}

class Post extends Eloquent
{
    protected $metaTable = 'posts_meta'; //optional.
}

$post = Post::find(1);
$post->name = 'hello world'; // model attribute
$post->content = 'some content goes here'; // meta data attribute
$post->save(); // save attributes to respective tables

$post = Post::find(1);
$post->name = 'hello world'; // model attribute
$post->setMeta('content', 'Some content here');
$post->save();

...
$post->setMeta([
    'content' => 'Some content here',
    'views' => 1,
]);
$post->save();

...
$post->setAttributes([
    'name' => 'hello world'; // model attribute
    'content' => 'Some content here',
    'views' => 1,
]);
$post->save();

$post = Post::find(1);
$post->name // model attribute
unset($post->content) // delete meta on save
$post->save();

$post->unsetMeta('content');
$post->save();

$post->unsetMeta('content,views');
// or
$post->unsetMeta('content|views');
// or
$post->unsetMeta('content', 'views');
// or array
$post->unsetMeta(['content', 'views']);

$post->save();

if (isset($post->content)) {

}

$post = Post::find(1);
dump($post->name);
dump($post->content); // will access meta.

$post = $post->getMeta('content');

$post = $post->getMeta('content', 'Something');

// using comma or pipe
$post = $post->getMeta('content|views');
// or an array
$post = $post->getMeta(['content', 'views']);

$metas = $post->getMeta();

$metas = $post->getMeta()->toArray();


$post = Post::meta()
    ->where(function($query){
          $query->where('posts_meta.key', '=', 'revision')
                ->where('posts_meta.value', '=', 'draft');
    })


$post = Post::with(['metas'])->get();

/* Post model */
public $hideMeta = true; // Do not add metas to array

   public $defaultMetaValues = [
      'is_user_home_sick' => false,
   ];