PHP code example of traineratwot / eloquent-meta

1. Go to this page and download the library: Download traineratwot/eloquent-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/ */

    

traineratwot / eloquent-meta example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Traineratwot\EloquentMeta\Traits\Meta;
use Traineratwot\EloquentMeta\Interfaces\UseMeta;

class Post extends Model implements UseMeta
{
    use Meta;

    protected $fillable = ['title', 'content'];
}

$post = Post::find(1);

// Получить конкретный ключ
$bio = $post->getMeta('profile', 'bio');

// Получить конкретный ключ с значением по умолчанию
$bio = $post->getMeta('profile', 'bio', 'No bio');

// Получить все метаданные колонки
$allProfileData = $post->getMeta('profile');

$post->setMeta('profile', 'bio', 'Мой профиль');
$post->setMeta('profile', 'avatar_url', 'https://example.com/avatar.jpg');

// Цепочка вызовов
$post->setMeta('settings', 'theme', 'dark')
     ->setMeta('settings', 'language', 'en')
     ->save();

// Добавить тег
$post->pushMeta('profile', 'tags', 'php');
$post->pushMeta('profile', 'tags', 'laravel');

// Результат: ['tags' => ['php', 'laravel']]

// Удалить конкретный ключ
$post->forgetMeta('profile', 'bio');

// Удалить всю ячейку метаданных
$post->forgetMeta('profile');

// Проверить наличие колонки
if ($post->hasMeta('profile')) {
    // ...
}

// Проверить наличие конкретного ключа
if ($post->hasMeta('profile', 'bio')) {
    // ...
}

$profileData = $post->getAllMeta('profile');
// Результат: ['bio' => '...', 'avatar_url' => '...']

// Сохранение SEO метаданных
$post->setMeta('seo', 'title', 'Мой пост')
     ->setMeta('seo', 'description', 'Описание поста')
     ->setMeta('seo', 'keywords', 'php, laravel')
     ->save();

// Сохранение пользовательских настроек
$user->setMeta('preferences', 'notifications', true)
     ->setMeta('preferences', 'theme', 'dark')
     ->setMeta('preferences', 'language', 'ru')
     ->save();

// Работа с массивами
$post->pushMeta('comments', 'ids', 1);
$post->pushMeta('comments', 'ids', 2);
$post->pushMeta('comments', 'ids', 3);

$commentIds = $post->getMeta('comments', 'ids');
// Результат: [1, 2, 3]
bash
php artisan vendor:publish --tag="eloquent-meta-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="eloquent-meta-config"