PHPackages                             gajosu/eloquent-preferences - 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. [Database &amp; ORM](/categories/database)
4. /
5. gajosu/eloquent-preferences

ActiveLibrary[Database &amp; ORM](/categories/database)

gajosu/eloquent-preferences
===========================

Preferences for Laravel Eloquent models

v1.0.2(3y ago)0750↓100%[4 PRs](https://github.com/gajosu/eloquent-preferences/pulls)MITPHPCI passing

Since Dec 21Pushed 2mo agoCompare

[ Source](https://github.com/gajosu/eloquent-preferences)[ Packagist](https://packagist.org/packages/gajosu/eloquent-preferences)[ Docs](https://github.com/gajosu/eloquent-preferences)[ RSS](/packages/gajosu-eloquent-preferences/feed)WikiDiscussions master Synced today

READMEChangelog (5)Dependencies (8)Versions (24)Used By (0)

Preferences for Laravel Eloquent models
=======================================

[](#preferences-for-laravel-eloquent-models)

[![Latest Version on Packagist](https://camo.githubusercontent.com/6437ccb3e2f5e0d857c6c4cddcd25d380ecb6dbe032dc0332e06bf5b0b708ac9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f67616a6f73752f656c6f7175656e742d707265666572656e6365732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/gajosu/eloquent-preferences)[![GitHub Tests Action Status](https://camo.githubusercontent.com/c488b0ef3c9db78776d59d9bef57bf26bd798cef5584a1b8c43914e919a4990f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f67616a6f73752f656c6f7175656e742d707265666572656e6365732f72756e2d74657374733f6c6162656c3d7465737473)](https://github.com/gajosu/eloquent-preferences/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/5fa1ab09bb7daccd569434cfa1601c09cfb36a7aed58f987c57aa3175a86e026/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f67616a6f73752f656c6f7175656e742d707265666572656e6365732f436865636b253230262532306669782532307374796c696e673f6c6162656c3d636f64652532307374796c65)](https://github.com/gajosu/eloquent-preferences/actions?query=workflow%3A%22Check+%26+fix+styling%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/3dee88a58ed24ed554ecb8a4d59e7f2d56034c7c2b5c5a73f122d1ebbe10d055/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f67616a6f73752f656c6f7175656e742d707265666572656e6365732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/gajosu/eloquent-preferences)

Use this library to bind multiple key/value pair preferences to your application's Eloquent models. Preferences are stored in your application's database so they can be easily stored and queried for. This library supports Eloquent 5 through 8 installed either standalone or as a part of the full Laravel framework. Issues and pull requests are welcome! See [CONTRIBUTING.md](https://github.com/gajosu/eloquent-preferences/blob/master/CONTRIBUTING.md) for more information.

- [Installation](#installation)
    - [Configuring In Laravel](#configuring-in-laravel)
    - [Configuring Without Laravel](#configuring-without-laravel)
    - [Enable Cache](#enable-cache)
- [Usage](#usage)
    - [Helper Methods](#helper-methods)
        - [Retrieving Preferences](#retrieving-preferences)
        - [Setting Preferences](#setting-preferences)
        - [Removing Preferences](#removing-preferences)
    - [Default Preference Values](#default-preference-values)
    - [Casting Preference Values](#casting-preference-values)
    - [Hidden Preference Attributes](#hidden-preference-attributes)

Installation
------------

[](#installation)

Run `composer require gajosu/eloquent-preferences` to download and install the library.

### Configuring In Laravel

[](#configuring-in-laravel)

1. Add `EloquentPreferencesServiceProvider` to `config/app.php`:

```
// ...

return [

    // ...

    'providers' => [

        // ...

        Gajosu\EloquentPreferences\EloquentPreferencesServiceProvider::class,
    ],

    // ...
];
```

2. Install the configuration and database migration files:

```
$ php artisan vendor:publish

```

3. Model preferences are stored in the "model\_preferences" database table by default. If you would like to use a different table then edit the "table" entry in `config/eloquent-preferences.php`.
4. Install the model preferences database:

```
$ php artisan migrate

```

### Configuring Without Laravel

[](#configuring-without-laravel)

1. Model preferences are stored in the "model\_preferences" database table by default. If you would like to use a different table then define the `MODEL_PREFERENCE_TABLE` constant at your project's point of entry with your preferred table name.
2. Install the model preferences database. There are a number of ways to do this outside of Laravel. Here's the schema blueprint to apply:

```
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Gajosu\EloquentPreferences\Preference;

// ...

Model::getConnectionResolver()
    ->connection()
    ->getSchemaBuilder()
    ->create((new Preference)->getQualifiedTableName(), function (Blueprint $table) {
        $table->increments('id');
        $table->string('preference');
        $table->string('value');
        $table->morphs('preferable');
        $table->timestamps();
    });
```

Enable Cache
------------

[](#enable-cache)

By default the cache is disabled, to enable it edit the "cache.enabled" entry in `config/eloquent-preferences.php` change the value to `true,`, you can also specify the cache prefix

```
'cache' => [
    'enabled' => true,
    'prefix' => 'eloquent-preferences',
]
```

Usage
-----

[](#usage)

Add the `HasPreferences` trait to the Eloquent models that you would like to have related preferences.

```
use Gajosu\EloquentPreferences\HasPreferences;

// ...

class MyModel extends Model
{
    use HasPreferences;

    // ...
}
```

This builds a polymorphic has-many relationship called "preferences" that you can query on your model like any other Eloquent relationship. Model preferences are modeled in the `Gajosu\EloquentPreferences\Preference` class. A preference object has `preference`, `value`, and Eloquent's built-in `created_at` and `updated_at` attributes. The `HasPreferences` trait can be used by any number of model classes in your application.

```
// Retrieving preferences via Eloquent
/** @var Gajosu\EloquentPreferences\Preference $myPreference */
$myPreference = MyModel::find($someId)->preferences()->where('preference', 'my-preference')->get();

// Saving preferences via Eloquent
$preference = new Preference;
$preference->preference = 'some preference';
$preference->value = 'some value';
$myModel->preferences()->save($preference);
```

Eloquent queries can be run directly on the `Preference` class as well.

```
/** @var Illuminate\Database\Eloquent\Collection|Gajosu\EloquentPreferences\Preference[] $preferences */
$preferences = Preference::whereIn('preference', ['foo', 'bar'])->orderBy('created_at')->get();
```

### Helper Methods

[](#helper-methods)

The `HasPreferences` trait has a number of helper methods to make preference management a little easier.

#### Retrieving Preferences

[](#retrieving-preferences)

Call the `getPreference($preferenceName)` or `prefers($preferenceName)` methods to retrieve that preference's value.

```
$numberOfFoos = $myModel->getPreference('number-of-foos');

$myModel->prefers('Star Trek over Star Wars') ? liveLongAndProsper() : theForceIsWithYou();
```

#### Setting Preferences

[](#setting-preferences)

Call the `setPreference($name, $value)` or `setPreferences($arrayOfNamesAndValues)` methods to set your model's preference values. Setting a preference either creates a new preference row if the preference doesn't exist or updates the existing preference with the new value.

```
$myModel->setPreference('foo', 'bar');

$myModel->setPreferences([
    'foo' => 'bar',
    'bar' => 'baz',
]);
```

#### Removing Preferences

[](#removing-preferences)

Call the `clearPreference($preferenceName)`, `clearPreferences($arrayOfPreferenceNames)`, or `clearAllPreferences()` methods to remove one, many, or all preferences from a model. Clearing preferences removes their associated rows from the preferences table.

```
$myModel->clearPreference('some preference');

$myModel->clearPreferences(['some preference', 'some other preference']);

$myModel->clearAllPreferences();
```

### Default Preference Values

[](#default-preference-values)

By default, `getPreference()` and `prefers()` return `null` if the preference is not stored in the database. There are two ways to declare default preference values:

1. Use an optional second parameter to `getPreference()` and `prefers()` to define a default value per call. If the preference is not stored in the database then the default value is returned.

```
// $myPreference = 'some default value'
$myPreference = $myModel->getPreference('unknown preference', 'some default value');
```

2. Avoid requiring extra parameters to every `getPreference()` and `prefers()` call by declaring a protected `$preference_defaults` array in your model containing a key/value pair of preference names and their default values. If the preference is not stored in the database but is defined in `$preference_defaults` then the value in `$preference_defaults` is returned. If neither of these exist then optional default value parameter or `null` is returned.

```
class MyModel extends Model
{
    use HasPreferences;

    // ...

    protected $preference_defaults = [
        'my-default-preference' => 'my-default-value',
    ];
}

// ...

// $myPreference = 'my-default-value'
$myPreference = $myModel->getPreference('my-default-preference');

// $myPreference = 'fallback value'
$myPreference = $myModel->getPreference('my-unstored-preference', 'fallback value');
```

Please note default preference values only apply when using the `getPreference()` and `prefers()` methods. Default values are not honored when retrieving preferences by Eloquent query.

### Casting Preference Values

[](#casting-preference-values)

Preferences are stored as strings in the database, but can be cast to different types when retrieved.

Declare a protected `$preference_casts` array in your model containing a key/value pair of preference names and the types to cast their values to. Preferences are stored and cast according to the same rules as [Eloquent's attribute type casts](https://laravel.com/docs/5.2/eloquent-mutators#attribute-casting).

```
class MyModel extends Model
{
    use HasPreferences;

    // ...

    protected $preference_casts = [
        'boolean-preference' => 'boolean',
        'floating-point-preference' => 'float',
        'date-preference' => 'date',
    ];
}
```

As with default values, casting preferences is only performed when using the `getPreference()`, `prefers()`, `setPreference()`, and `setPreferences()` helper methods.

### Hidden Preference Attributes

[](#hidden-preference-attributes)

By default all preference model attributes are visible when exporting to JSON. However it is possible to declare hidden attributes that act in the same manner as [Eloquent's hidden attributes](https://laravel.com/docs/5.2/eloquent-serialization#hiding-attributes-from-json). There are two ways to declare which preference attributes to hide from JSON export:

1. If this library is being used in a Laravel project then declare hidden attributes in the "hidden-attributes" key in `config/eloquent-preferences.php`.

```
return [

    // ...

    'hidden-attributes' => ['created_at', 'updated_at'],

    // ...
];

```

2. If this library is being used outside the Laravel framework then define the `MODEL_PREFERENCE_HIDDEN_ATTRIBUTES` constant at your project's point of entry with a comma-separated list of attributes to hide from JSON export.

```
const MODEL_PREFERENCE_HIDDEN_ATTRIBUTES = 'created_at,updated_at';
```

### Original Author

[](#original-author)

This library was created by [Klaude](https://github.com/klaude) and is licensed under the [MIT license](LICENSE.md).

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance57

Moderate activity, may be stable

Popularity14

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~160 days

Recently: every ~1 days

Total

16

Last Release

1337d ago

Major Versions

v0.7.0 → v1.0.02022-07-24

### Community

Maintainers

![](https://www.gravatar.com/avatar/6ba7af87881476b7e21c68b907b3b0615a3213575e3dc896ac42cfebde210e81?d=identicon)[gajosu](/maintainers/gajosu)

---

Top Contributors

[![gajosu](https://avatars.githubusercontent.com/u/7597189?v=4)](https://github.com/gajosu "gajosu (45 commits)")[![klaude](https://avatars.githubusercontent.com/u/45157?v=4)](https://github.com/klaude "klaude (41 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (9 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (6 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (1 commits)")

---

Tags

laraveleloquentpreferences

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/gajosu-eloquent-preferences/health.svg)

```
[![Health](https://phpackages.com/badges/gajosu-eloquent-preferences/health.svg)](https://phpackages.com/packages/gajosu-eloquent-preferences)
```

###  Alternatives

[rtconner/laravel-likeable

Trait for Laravel Eloquent models to allow easy implementation of a 'like' or 'favorite' or 'remember' feature.

402385.8k5](/packages/rtconner-laravel-likeable)[klaude/eloquent-preferences

Preferences for Laravel Eloquent models

3016.5k](/packages/klaude-eloquent-preferences)[czim/laravel-filter

Filter for Laravel Eloquent queries, with support for modular filter building

8972.4k3](/packages/czim-laravel-filter)[cviebrock/eloquent-typecast

Trait for Eloquent models to force type-casting on retrieved values

2467.2k](/packages/cviebrock-eloquent-typecast)[phaza/single-table-inheritance

Single Table Inheritance Trait

1515.8k](/packages/phaza-single-table-inheritance)

PHPackages © 2026

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