PHPackages                             zoha/laravel-meta - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. zoha/laravel-meta

ActivePackage[Utility &amp; Helpers](/categories/utility)

zoha/laravel-meta
=================

a package for working with models meta

v2.0.2(2y ago)236121.7k↓31.2%29[3 issues](https://github.com/Zoha/laravel-meta/issues)MITPHPCI failing

Since Apr 17Pushed 7mo ago5 watchersCompare

[ Source](https://github.com/Zoha/laravel-meta)[ Packagist](https://packagist.org/packages/zoha/laravel-meta)[ RSS](/packages/zoha-laravel-meta/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (3)Versions (16)Used By (0)

Laravel Meta
============

[](#laravel-meta)

a laravel package for working with meta !

[![Package Image](https://raw.githubusercontent.com/Zoha/files/master/larave-meta/images/cover%20image.jpg)](https://github.com/Zoha/laravel-meta "Go to GitHub repo")

[![Zoha - laravel-meta](https://camo.githubusercontent.com/f1ed75e68b0b1cd9ac8f7a70d1938246ad858d1685f40de6bfea25a5098afa9a/68747470733a2f2f696d672e736869656c64732e696f2f7374617469632f76313f6c6162656c3d5a6f6861266d6573736167653d6c61726176656c2d6d65746126636f6c6f723d726564266c6f676f3d676974687562)](https://github.com/Zoha/laravel-meta "Go to GitHub repo")[![stars - laravel-meta](https://camo.githubusercontent.com/f8492c18f43d1bd8699129dc7daec4ddb00178a3d9f9a6f105866ef89bd70cd2/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f5a6f68612f6c61726176656c2d6d6574613f7374796c653d736f6369616c)](https://github.com/Zoha/laravel-meta)[![forks - laravel-meta](https://camo.githubusercontent.com/b6a3b2dd5dd116644b4ff9bbdd830d38df1bf89fed48c40fae3cf017250e8f8f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f666f726b732f5a6f68612f6c61726176656c2d6d6574613f7374796c653d736f6369616c)](https://github.com/Zoha/laravel-meta)[![GitHub tag](https://camo.githubusercontent.com/4695da9966446d95cd39d46023a118f1b5aba54f587d65306ce94c9024699028/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f7461672f5a6f68612f6c61726176656c2d6d6574613f696e636c7564655f70726572656c65617365733d26736f72743d73656d76657226636f6c6f723d6379616e)](https://github.com/Zoha/laravel-meta/releases/)[![License](https://camo.githubusercontent.com/d6bc2b26794002c24d023acaab01b6dbb953c57ab9cb80ba5b8aa2f2bd5de99a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c7565)](#license)

Page Contents
=============

[](#page-contents)

1. [Introduction](#introduction)
2. [Features](#features)
3. [Installation](#installation)
4. [Basic Methods](#basic-methods)
    - [Create New Meta](#create-new-meta)
    - [Update Meta](#update-meta)
    - [Create Or Update Meta](#create-or-update-meta)
    - [Get Meta](#get-meta)
    - [Get Metas](#get-metas)
    - [Delete Meta](#delete-meta)
    - [Check Meta Exists Or Not](#check-meta-exists-or-not)
    - [Increase Meta](#increase-meta)
    - [Decrease Meta](#decrease-meta)
5. [Clauses](#clauses)
    - [Where Meta Clause](#where-meta-clause)
    - [Where Meta In Clause](#where-meta-in-clause)
    - [Where Meta Between Clause](#where-meta-between-clause)
    - [Where Meta Null Clause](#where-meta-null-clause)
    - [Where Meta Has Clause](#where-meta-has-clause)
    - [Order By Meta](#order-by-meta)
    - [Eager Loading](#eager-loading)
6. [Other Methods And Features](#other-methods-and-features)
    - [Notes](#notes)
    - [Data Type](#data-type)
    - [Custom Meta Table](#custom-meta-table)
    - [Meta Model](#meta-model)
    - [Meta Table](#meta-table)
7. [License](#license)
8. [Contributing](#contributing)

Introduction
============

[](#introduction)

[![gif-file](https://raw.githubusercontent.com/ZohaBanam/files/master/larave-meta/images/example.gif)](https://raw.githubusercontent.com/ZohaBanam/files/master/larave-meta/images/example.gif)

Sometimes our models in laravel needs a lot of information that should be stored in the database. For example, Suppose you want to create a blog and add a model for posts on this blog. The most important information that this model will need is its title and content. But this model may also have more information, Such as the number of likes, download links, thumbnails, views, and more. When the amount of this information is high, We need to create more columns for the model table, Which if there are too many, Will be difficult. Additionally, Each of these posts may have their own unique information that the rest of the posts do not need. In such cases, This package will help. If we want to explain this package simply: Laravel Meta allows you to store information for each of your models and easily access them without having to create new columns for this information in the database tables. If you still do not notice it, Just look at the examples below.

Features
========

[](#features)

- It is easy to store and receive meta for each model
- An alternative to creating many columns in the database table
- Minimum number of queries and complete optimization
- Ability to filter database records by meta

Installation
============

[](#installation)

First , Require this package with composer

```
 $ composer require zoha/laravel-meta

```

If you Use Laravel &lt;= 5.4 add the ServiceProvider and Alias in config/app.php

```
'providers' => [
    ...
    Zoha\Meta\MetaServiceProvider::class,
    ...
]
'aliases' => [
    ...
    'Meta' => Zoha\Meta\Facades\MetaFacade::class,
    ...
]
```

And execute migrate command to migrate meta table

```
 $ php artisan migrate

```

And then to add meta functionality to each of your models, You just need to extends it from MetableModel instead of the Model.

```
use Zoha\MetableModel;

class Post extends MetableModel
{
    ...
}
```

Or you can use Metable trait instead :

```
use Zoha\Metable;

class Post extends Model
{
    use Metable;
    ...
}
```

##### Optional Section

[](#optional-section)

You can publish meta config file using this command :

```
 $ php artisan vendor:publish --provider="Zoha\Meta\MetaServiceProvider" --tag=config

```

In this file you can change default meta table ( default: meta ) Or you can [customize meta table for a specific model](#custom-meta-table)

That's it! Now you can use all of the Laravel meta features

> In all of the examples below, we assume that the $post is set to Post::first() which Post model is an example model

Basic Methods
=============

[](#basic-methods)

### Create New Meta

[](#create-new-meta)

For create a meta you can use `createMeta` on Model :

```
$post->createMeta('key' , 'value');
```

Or you can create multiple meta like this :

```
$post->createMeta([
    'key1' => 'value1',
    'key2' => 'value2'
]);
```

@return : `createMeta` method returns **true** if the meta creation is performed successfully and **false** otherwise

> `addMeta` method is alias of `createMeta` method

### Update Meta

[](#update-meta)

For update a meta you can use `updateMeta` on Model :

```
$post->updateMeta('key' , 'new value');
```

Or you can update multiple meta like this :

```
$post->updateMeta([
    'key1' => 'new value 1',
    'key2' => 'new value 2'
]);
```

@return : If the update was successful `updateMeta` return **true** . but if meta already not exists or updating was faild **false** will be returned

### Create Or Update Meta

[](#create-or-update-meta)

For create or update meta use `setMeta` method this method will update meta or create a new one if not exists yet

```
$post->setMeta('key' , 'value'); // create meta
$post->setMeta('key' , 'new value'); // update meta
```

Or you can set multiple meta like this

```
$post->setMeta([
    'key1' => 'value 1',
    'key2' => 'value 2'
]);
```

@return : `setMeta` returns **true** if it is successful. Otherwise it will return **false**

Or instead of this method, You can set meta using **meta property** like this :

```
$post->meta->key1 = 'value';
$post->meta->key2 = 'value2';
$post->meta->save();
```

### Get Meta

[](#get-meta)

`getMeta` method will return meta value :

```
//return meta value or null if meta not exists
$post->getMeta('key');

// return value or 'default value ' if not exists or value is null
$post->getMeta('key' , 'default value') ;
```

Also you can get meta values using **meta property** :

```
$post->meta->key; // return meta value
```

### Get Metas

[](#get-metas)

`getMetas` method will return all metas as a collection :

```
// return a collection of all metas for this model
// no meta yet ? -> empty collection
$post->getMetas() ;
```

### Delete Meta

[](#delete-meta)

For delete meta use `deleteMeta` method

```
$post->deleteMeta(); // delete all meta of this model

$post->deleteMeta('key'); // delete a specific meta
```

Or you can use `unsetMeta` method instead . both of methods are the same. `truncateMeta` also delete all meta of specific model :

```
$post->truncateMeta(); // delete all model meta
```

### Check Meta Exists Or Not

[](#check-meta-exists-or-not)

You can use `hasMeta` method if you want to check there is a particular meta or not ( if meta exists but value equals to null false will be returned )

```
$post->hasMeta(); // return true if this model has at least one meta
$post->hasMeta('key'); // return true or false
```

The second argument specifies whether or not to accept null values . If you pass **true** for second argument , and meta exists even if value equals to null true will be returned

```
$post->setMeta('key' , null); // set key to null
$post->hasMeta('key'); // return false
$post->hasMeta('key' , true); // return true
```

If you want to specify that a particular post has a specific meta, even if its value is null , use the `existsMeta` method.

```
$post->setMeta('key' , null); // set key to null
$post->existsMeta('key'); // return true
```

### Increase Meta

[](#increase-meta)

You can simply increase meta value using `increaseMeta` method. Note that incrementing a float value will not increment the decimal unless specified.

```
$post->setMeta('key' , 3);
$post->increaseMeta('key'); // meta value will change to 4

$post->setMeta('key' , 3.5);
$post->increaseMeta('key'); // meta value will change to 4.5

$post->setMeta('key' , 3.5);
$post->increaseMeta('key' , .1); // meta value will change to 3.6

$post->setMeta('key2' , 'not integer value');
$post->increaseMeta('key2'); // meta value will not change
```

You can pass second argument for detemine increase step

```
$post->setMeta('key' , 3);
$post->increaseMeta('key',3); // meta value will change to 6
```

### Decrease Meta

[](#decrease-meta)

You can simply decrease meta value using `decreaseMeta` method. Note that decrementing a float value will not decrement the decimal value unless specified.

```
$post->setMeta('key' , 3);
$post->decreaseMeta('key'); // meta value will change to 2

$post->setMeta('key' , 3.5);
$post->decreaseMeta('key'); // meta value will change to 2.5

$post->setMeta('key' , 3.5);
$post->decreaseMeta('key', .1); // meta value will change to 3.4

$post->setMeta('key2' , 'not integer value');
$post->decreaseMeta('key2'); // meta value will not change
```

And you can pass second argument for detemine decrease step

```
$post->setMeta('key' , 3);
$post->decreaseMeta('key',3); // meta value will change to 0
```

Clauses
=======

[](#clauses)

### Where Meta Clause

[](#where-meta-clause)

Filter items by meta value :

```
$result = Post::whereMeta('key','value');
// you can use operator :
$result = Post::whereMeta('key', '>' , 100);

// you can use multiple whereMeta Clause
$result = Post::whereMeta('key', '>' , 100)
                            ->whereMeta('key' , '' , 100)
                            ->orWhereMeta('key' , '' , 100);
});
```

You can also pass a array for filter result :

```
// all of below conditions will converted to 'AND'
$result = Post::whereMeta([
    'key1' => 'value1',
    [ 'key2' , '!=' , 'value2' ],
    [ 'key3' , 'value3' ]
]);
```

You can aslso use orWhere for mulitple or where clause :

```
$result = Post::orWhereMeta([
    'key1' => 'value1',
    [ 'key2' , '!=' , 'value2' ],
    [ 'key3' , 'value3' ]
]);
```

> **You can use branched filters for all meta clauses**

### Where Meta In Clause

[](#where-meta-in-clause)

`whereMetaIn` and `whereMetaNotIn` clauses :

```
$result = Post::whereMetaIn('key', ['value1' , 'value2']);
$result = Post::whereMetaNotIn('key', ['value1' , 'value2']);

// multiple clauses
$result = Post::whereMetaIn('key', [1,2])
                            ->whereMetaIn('key2' , [1,2]);

// 'orWhere' clauses
$result = Post::whereMetaNotIn('key', [1,2,3])
                            ->orWhereMetaIn('key2', [1,2])
                            ->orWhereMetaNotIn('key3', [1,2]);
```

### Where Meta Between Clause

[](#where-meta-between-clause)

`whereMetaBetween` and `whereMetaNotBetween` clauses :

```
$result = Post::whereMetaBetween('key', [0,100]);
$result = Post::whereMetaNotBetween('key', [0,100]);

// multiple clauses
$result = Post::whereMetaBetween('key', [100,200])
                            ->whereMetaBetween('key2' , [100,200]);

// 'orWhere' clauses
$result = Post::whereMetaNotBetween('key', [1000,8000])
                            ->orWhereMetaBetween('key2', [1,5])
                            ->orWhereMetaNotBetween('key3', [0,100]);
```

### Where Meta Null Clause

[](#where-meta-null-clause)

`whereMetaNull` and `whereMetaNotNull` clauses :

```
$result = Post::whereMetaNull('key');
$result = Post::whereMetaNotNull('key');

// multiple clauses
$result = Post::whereMetaNull('key')
                            ->whereMetaNull('key2');

// 'orWhere' clauses
$result = Post::whereMetaNotNull('key')
                            ->orWhereMetaNull('key2')
                            ->orWhereMetaNotNull('key3');
```

### Where Meta Has Clause

[](#where-meta-has-clause)

`whereMetaHas` and `whereMetaDoesntHave` clauses :

```
//filter records that has at least one meta
$result = Post::whereMetaHas();

$result = Post::whereMetaHas('key');
$result = Post::whereMetaHas('key' , true); //count null values

$result = Post::whereMetaDoesntHave('key');
$result = Post::whereMetaDoesntHave('key' , true); //count null values

// multiple clauses
$result = Post::whereMetaHas('key')
                            ->whereMetaDoesntHave('key2');

// 'orWhere' clauses
$result = Post::whereMetaDoesntHave('key')
                            ->orWhereMetaHas('key2')
                            ->orWhereMetaDoesntHave('key3');
```

### Order By Meta

[](#order-by-meta)

You Can Sort Database Results Using `orderByMeta` clause :

```
Post::orderByMeta('price')->get();

Post::orderByMeta('price' , 'desc')->get();

Post::orderByMeta('price')->orderByMeta('likes' , 'desc')->get();
```

### Eager Loading

[](#eager-loading)

If you call `$post->getMeta('key')` for the first time all of this model meta will be loaded ( once ) and if you try to get another meta from this model another query will not be executed and meta value will loaded from previous query. But if you try to get meta in another model, Another query will be executed for new model . If you want get all meta of all models in one query you can use eager loading of meta . you just need to call `withMeta` scope like this :

```
$posts = Post::withMeta()->get(); // will return all posts results with their meta values
```

Note that `with('meta')` will not work

Other Methods And Features
==========================

[](#other-methods-and-features)

### Notes

[](#notes)

- by default all collections , arrrays and json values will convert to collection when you try to get them.
- all `[]` , `"{}"` , `"[]"` and `null` values will be considered null.
- If one of the items in the metable model is deleted, All the meta related to that item will be deleted too.

### Data Type

[](#data-type)

All of `setMeta` , `getMeta` , `updateMeta` And `createMeta` methods accept a third argument that determine meta data type . there are some examples of this feature :

> Available data types : `string` , `integer` , `float` , `null` , `collection` , `json` `array` , `boolean`.

In `setMeta` method

```
$post->setMeta('key' , '123' , 'integer');
$post->meta->key; // 123 ( integer )

$post->setMeta('key' , '123.45' , 'integer');
$post->meta->key; // 123 ( integer - decimal dropped)

$post->setMeta('key' , '123.45' , 'float');
$post->meta->key; // 123.45 ( float )
//----------------------------------
$post->setMeta('key' , [1,2,3] , 'json');
$post->meta->key; // "[1,2,3]" ( string - json )
//----------------------------------
$post->setMeta([
    'key1' => 'value',
    'key2' => 2
    'key3' => [1,2,3]
],'string' ); // all values will converted to string when you try to get them
$post->meta->key2; // "2" ( string )
$post->meta->key3; // "[1,2,3]" ( string json )
```

Third argument in `createMeta` and `updateMeta` methods is the same of `setMeta` method

In `getMeta` method

```
$post->setMeta('key' , 123);
$post->getMeta('key' , 'null' , 'string'); // "123" (string)
//----------------------------------
$post->setMeta('key' , [1,2,3] , 'string');
$post->getMeta('key' , 'null'); // "[1,2,3]" (string)
$post->getMeta('key' , 'null' , 'array'); // [1,2,3] (array)
$post->getMeta('key' , 'null' , 'boolean'); // true (boolean)
```

### Custom Meta Table

[](#custom-meta-table)

By default, all meta-data for all models will be stored in the `meta` database table. But if you want, you can use a separate table for a particular model.

For example, you have `Post`, `Comment` and `User` models

You want to store all posts and comments meta in default table but the user's meta tags are in a special table To do this you have to take four steps :

First Step : you should publish package config file using this command :

```
$ php artisan vendor:publish --provider="Zoha\Meta\MetaServiceProvider" --tag=config

```

This command will place a file named `meta.php` in your config folder

Second Step : open config file in `tables` array you find a custom array . in this array you can add new tables name . for our example we add `users_meta` in this array to handle users meta :

```
'tables' => [
    'default' => 'meta',
    'custom'  => [
        'users_meta'
    ],
]
```

Third Step : you need to run migrate command to create new table .

```
$ php artisan migrate

```

If you have already migrated Meta migration, you should rollback this migrations and migrate it again ( to create new tables )

Final Step : now that the new table is made, you can introduce it to the `User` model (or any model you want) to handle its meta with this table . like this :

```
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use \Zoha\Metable;

    protected $metaTable = 'users_meta';
}
```

### Meta Model

[](#meta-model)

you are free to use meta model in your project

```
use Zoha\Meta\Models\Meta;
$count = Meta::count();
```

Note : If you change meta values using meta model ( change database directly ) meta valuse that was loaded before will not be updated . If you want to update them you should call `refreshLoadedMeta` metahod :

```
use Zoha\Meta\Models\Meta;

$post->meta->key1; // exmaple : return 'test'
Meta::truncate();
$post->meta->key1; // still return 'test'

$post->refreshLoadeMeta();
$post->meta->key1; // will return null
```

### Meta Table

[](#meta-table)

The structure of the meta table is this :

```
Schema::create('meta', function (Blueprint $table) {
    $table->increments('id');
    $table->string('key',110);
    $table->text('value')->nullable();
    $table->string('type')->default(Meta::META_TYPE_STRING);
    $table->boolean('status')->default(true);
    $table->string('owner_type',80);
    $table->integer('owner_id');
    $table->unique(['key','owner_type','owner_id']);
    $table->timestamps();
});
```

License
=======

[](#license)

[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)

contributing
============

[](#contributing)

This project is open for you [contribution](https://github.com/Zoha/laravel-meta/blob/master/CONTRIBUTING.md)

###  Health Score

51

—

FairBetter than 96% of packages

Maintenance44

Moderate activity, may be stable

Popularity51

Moderate usage in the ecosystem

Community22

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 88% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~181 days

Recently: every ~321 days

Total

13

Last Release

779d ago

Major Versions

v1.9 → v2.0.02022-04-04

### Community

Maintainers

![](https://www.gravatar.com/avatar/3f80b35562f58569f89e85dd0f5e10b7ce7469248aa24eb13192a064310ef92b?d=identicon)[ZohaBanam](/maintainers/ZohaBanam)

---

Top Contributors

[![Zoha](https://avatars.githubusercontent.com/u/16442858?v=4)](https://github.com/Zoha "Zoha (147 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (8 commits)")[![necenzurat](https://avatars.githubusercontent.com/u/145449?v=4)](https://github.com/necenzurat "necenzurat (4 commits)")[![eduPHP](https://avatars.githubusercontent.com/u/12203605?v=4)](https://github.com/eduPHP "eduPHP (3 commits)")[![HasanEksi](https://avatars.githubusercontent.com/u/11349158?v=4)](https://github.com/HasanEksi "HasanEksi (2 commits)")[![mhmiton](https://avatars.githubusercontent.com/u/38657829?v=4)](https://github.com/mhmiton "mhmiton (1 commits)")[![AxissXs](https://avatars.githubusercontent.com/u/12409743?v=4)](https://github.com/AxissXs "AxissXs (1 commits)")[![XGhozt](https://avatars.githubusercontent.com/u/5670495?v=4)](https://github.com/XGhozt "XGhozt (1 commits)")

---

Tags

laravelmetametablemodels-metapackagephplaravelpackagedatameta

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/zoha-laravel-meta/health.svg)

```
[![Health](https://phpackages.com/badges/zoha-laravel-meta/health.svg)](https://phpackages.com/packages/zoha-laravel-meta)
```

###  Alternatives

[iteks/laravel-enum

A comprehensive Laravel package providing enhanced enum functionalities, including attribute handling, select array conversions, and fluent facade interactions for robust enum management in Laravel applications.

2516.7k](/packages/iteks-laravel-enum)[jaybizzle/hasmeta

Access model meta data as if it was a property on your model

291.9k](/packages/jaybizzle-hasmeta)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
