PHP code example of danielefavi / laravel-metadata

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

    

danielefavi / laravel-metadata example snippets


$user->saveMeta('age', 25); // storing
$user->saveMeta('dog_name', 'Buddy'); // storing

$age = $user->getMeta('age');

    'providers' => [
        // ...
        DanieleFavi\Metadata\MetaServiceProvider::class,
    ],

use DanieleFavi\Metadata\HasMetadata; // to add in your model

class User extends Authenticatable
{
    use HasFactory;
    use HasMetadata; // to add in your model
    
    // ...
}

$user->saveMeta('phone_number', '111222333'); // storing a value
$user->saveMeta('color_preference', ['orange', 'yellow']); // storing an array

$user->saveMetas([
    'phone_number' => '333222111',
    'color_preference' => ['red', 'green'],
    'address' => '29 Arlington Avenue',
]);

$phoneNumber = $user->getMeta('phone_number'); // the value of $phoneNumber is '111222333'

// Default value in case the metadata has not been found (default: null)
$anotherMeta = $user->getMeta('another_meta', 10);

// return an array key => value with the metadata specified for the given keys
$metas = $user->getMetas(['phone_number', 'address']);
// the value of the $metas is an array key => value:
// [
//     'phone_number' => '111222333',
//     'address' => '29 Arlington Avenue'
// ]

// return an array key => value containing all metadata of the user model
$metas = $user->getMetas();

$metaObj = $user->getMetaObj('address');

// delete a single metadata
$user->deleteMeta('address');

// delete multiple metadata
$user->deleteMeta(['phone_number', 'address']);

// delete all metadata
$user->deleteAllMeta();

$list = $user->metas;

$users = User::metaWhere('hair_color', 'brown')
            ->orMetaWhere('hair_color', 'pink')
            ->get();

$users = User::metaWhere('dog_name', 'charlie')
            ->where(function($query) {
                return $query->metaWhere('hair_color', 'brown')
                    ->orMetaWhere('hair_color', 'pink');
            })
            ->get();

$users = User::whereHas('metas', function($query) {
    $query->where('key', 'hair_color');
    $query->where('value', json_encode('blue')); // remember to json_encode the value!!!
})->get();


$users = User::with('metas')->get();

$user = User::find(1);

$user->load('metas');
sh
php artisan migrate