A laravel package to handle model specific additional meta fields in an elegant way.

Overview

Laravel Meta Fields

A php package for laravel framework to handle model meta data in a elegant way.

Installation

Require the package using composer:

composer require touhidurabir/laravel-meta-fields

To publish the config and migration file:

php artisan vendor:publish --provider="Touhidurabir\MetaFields\MetaFieldsServiceProvider"

Configuration

The meta-field config file contains the configuration option of meta table name and meta model. It also provides an cast option that will be applied to meta table's metas column which contains the meta fields as array, object or collection(Laravel Collection) . Read the config file to know more details .

Usage

To use with a model , just use the HasMeta tarit.



namespace App\Models;

use Touhidurabir\MetaFields\HasMeta;

class User extends Authenticatable {

    use HasMeta;
}

And then use it in such way as

$user = User::create([...]);
$meta = $user->storeMeta([]);

As this package use the Illuminate\Database\Eloquent\Relations\MorphMany to maintain a one to many poly morphic relation between the parent model and metas , it is possible to restrict if a model can have multiple metas or not by overriding the HasMeta traits canHaveMultipleMetas method my returning false as :

/**
 * Define if a model can have multiple meta data records
 *
 * @return bool
 */
public function canHaveMultipleMetas() {

    return false;
}

Also the metas are state aware , that is if the associated parent model got deleted, force deleted or restored , meta recored will follow the same model record state . This is by default enabled . To disable this override syncWithParent directly in the model calss to return false .

/**
 * Define if the metas associated with a parent model sync with parents state
 * The sync up behaviour apply to parent's [delete, force delete and restore] events
 * 
 * @return bool
 */
public function syncWithParent() {

    return true;
}

As metas are managed as Polymorphic Relations and use laravel's MorphMany relations, all models related functionality are availabel . But this package also provide some additional methods such .

To Update, the updateMeta method such as :

$user->updateMeta([])

NOTE : if model can have multiple meta records, calling updateMeta will throw exception as not possible to know which one of multiple meta records to update .

To delete, the deleteMeta methods can be used as :

$user->deleteMeta()

By default metas will be deleted as soft deleted record as this package uses softDelets trait on meta model . to force delete, pass true as the only argument to deleteMeta method .

This package Provide some handly out of box methods to handle metas of a model instance . such as

To Determine if model instance has any meta associated

$user->hasMeta()

which will return boolean based on any meta associated with or not.

To Determine if aspecific meta fields associated

To deletermine if a specific metafields associated with model instance, follow as :

$user->isMetaAssociated('field_name')

By default it will return boolean to indicate if there is any associated meta field associate with this one . But if need those records also , pass true as the second argument which will return collection of matched metas or empty collection if none found.

To get the meta value

To get the meta value of a a given field for a model instance, follow as :

$user->metaValue('field_name')

By default, it will only pass one single and first match value even if there is multiple of of meta records that contains the give meta fields . to get all pass true as the second argument which will return an array as list of all values .

Storing Metas and Validation

To make the storing and validattion process of meta easier , this package provide another trait named WithMetaFields whcih can be used with the FormRequest class . This trait has as an abstract method metaRules that must be defined which will contains the validation rules for metas . The package will also use the field name defined in this methods to determine the meta fields .

Use the trait in the FormRequest class as such :

use Illuminate\Foundation\Http\FormRequest;
use Touhidurabir\MetaFields\WithMetaFields;

class StoreUser extends FormRequest {

    use WithMetaFields;
    
    /**
     * The meta fields validation rules
     *
     * @return array
     */
    public function metaRules() : array {

        return [
            'bio' => [
                ...
            ],
            'dob' => [
                ...
            ],
        ];
    }
}

And then from the controller class,

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(StoreUser $request) {
    
    // create user
    $user = User::create(...);

    // store meta for user 
    $metas = $request->metas($request->validated()); // this array[$request->validated()] argument is optional
    $user->storeMeta($metas);
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

You might also like...
Handle all the hard stuff related to EU MOSS tax/vat regulations, the way it should be.

VatCalculator Handle all the hard stuff related to EU MOSS tax/vat regulations, the way it should be. Integrates with Laravel and Cashier — or in a st

Save Model is a Laravel package that allows you to save data in the database in a new way.

Save Model is a Laravel package that allows you to save data in the database in a new way. No need to worry about $guarded and $fillable properties in the model anymore. Just relax an use Save Model package.

Laravel-model-mapper - Map your model attributes to class properties with ease.
Laravel-model-mapper - Map your model attributes to class properties with ease.

Laravel Model-Property Mapper This package provides functionality to map your model attributes to local class properties with the same names. The pack

Laravel SEO - This is a simple and extensible package for improving SEO via meta tags, such as OpenGraph tags.

This is a simple and extensible package for improving SEO via meta tags, such as OpenGraph tags.

HTML Meta Tags management package available for for Laravel 5.*

HTML Meta Tags management package available for Laravel 5/6/7/8 With this package you can manage header Meta Tags from Laravel controllers. If you wan

Laravel package meta 🧡
Laravel package meta 🧡

About hwa-meta is a meta package. It helps us to build and develop faster with pre-built functions. This saves a lot of time on future projects. We sh

The main MageSuite (meta)package to rule them all
The main MageSuite (meta)package to rule them all

A Magento 2 extension ecosystem providing UX/performance improvements and many new features. This is a core metapackage which you should install in or

An elegant package for integrate laravel with openwa
An elegant package for integrate laravel with openwa

Whatsapp Laravel An elegant package to integrate Laravel with Whatsapp automate Features Function Reference Send text Send contact Send media (doc, im

Cache-purge-helper - Additional instances where nginx-helper and lscache plugin should be purged.

cache-purge-helper Additional instances where nginx-helper and lscache plugin should be purged. Install Extract the zip file. Upload them to /wp-conte

Releases(1.0.1)
Owner
Touhidur Rahman
Husband, father, big time documentary tv series lover and software engineer . Passionate about PHP, Laravel, Ruby on Rails, Vue.js and C/C++ . Learning Rust .
Touhidur Rahman
A simple laravel package to handle multiple key based model route binding

Laravel Model UUID A simple package to handle the multiple key/column based route model binding for laravel package Installation Require the package u

null 13 Mar 2, 2022
A laravel package to handle cascade delete and restore on model relations.

Laravel Model Soft Cascade A laravel package to handle cascade delete and restore on model relations. This package not only handle the cascade delete

Touhidur Rahman 18 Apr 29, 2022
A Laravel package to manage versions of endpoints in an elegant way

API version control A Laravel package to manage versions of endpoints in an elegant way Two ways to manage the versions of your endpoints Option 1: Ve

Reindert 156 Dec 9, 2022
Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords.

Laravel Otpify ?? Introduction Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords. Install

Prasanth Jayakumar 2 Sep 2, 2022
A simple laravel state machine to handle model transitions, based on a pre-defined list of rules

A simple state machine that allows transitioning model states based on pre-defined rules. Installation You can install the package via composer: compo

Jack Mollart 18 Apr 2, 2022
Validate your input data in a simple way, an easy way and right way. no framework required. For simple or large. project.

wepesi_validation this module will help to do your own input validation from http request POST or GET. INTEGRATION The integration is the simple thing

Boss 4 Dec 17, 2022
A laravel package to generate model hashid based on model id column.

Laravel Model Hashid A package to generate model hash id from the model auto increment id for laravel models Installation Require the package using co

Touhidur Rahman 13 Jan 20, 2022
A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Touhidur Rahman 17 Jan 20, 2022
[READ ONLY] WordPress-specific Comment data model

Comments WordPress-specific Comment Data Model Install Via Composer composer require pop-wp-schema/comments Development The source code is hosted on t

PoP WordPress Schema 2 Dec 14, 2022
Handle all the hard stuff related to EU MOSS tax/vat regulations, the way it should be.

VatCalculator Handle all the hard stuff related to EU MOSS tax/vat regulations, the way it should be. Integrates with Laravel and Cashier — or in a st

Dries Vints 1.1k Jan 5, 2023