PHPackages                             klaude/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. klaude/eloquent-preferences

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

klaude/eloquent-preferences
===========================

Preferences for Laravel Eloquent models

v0.6.0(2y ago)3016.5k6[1 PRs](https://github.com/klaude/eloquent-preferences/pulls)MITPHPCI failing

Since Dec 21Pushed 2y ago4 watchersCompare

[ Source](https://github.com/klaude/eloquent-preferences)[ Packagist](https://packagist.org/packages/klaude/eloquent-preferences)[ Docs](https://github.com/klaude/eloquent-preferences)[ RSS](/packages/klaude-eloquent-preferences/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (4)Versions (15)Used By (0)

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

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

[![Build Status](https://camo.githubusercontent.com/3b12c94522dc42c06a96349eba2337797f3a13a5d3fd64277c7730c4e18b23cb/68747470733a2f2f7472617669732d63692e6f72672f6b6c617564652f656c6f7175656e742d707265666572656e6365732e706e67)](https://travis-ci.org/klaude/eloquent-preferences)[![Latest Stable Version](https://camo.githubusercontent.com/2597c0b784b07ecc419fec7eccd25d714c043cf5f99828ad2edca139dbbace10/68747470733a2f2f706f7365722e707567782e6f72672f6b6c617564652f656c6f7175656e742d707265666572656e6365732f762f737461626c65)](https://packagist.org/packages/klaude/eloquent-preferences)[![Total Downloads](https://camo.githubusercontent.com/ac9d7aeb0a379e1ed2d557f92085b5d38412a64302d18c039cb2967cc10a0c6c/68747470733a2f2f706f7365722e707567782e6f72672f6b6c617564652f656c6f7175656e742d707265666572656e6365732f646f776e6c6f616473)](https://packagist.org/packages/klaude/eloquent-preferences)[![Latest Unstable Version](https://camo.githubusercontent.com/34c4505c331f7a7e603b664c70d7134d2c440919e7b2f45a920500f05e8f627c/68747470733a2f2f706f7365722e707567782e6f72672f6b6c617564652f656c6f7175656e742d707265666572656e6365732f762f756e737461626c65)](https://packagist.org/packages/klaude/eloquent-preferences)[![License](https://camo.githubusercontent.com/3f1e6b8509f11580c6886fc59022ca9e5d4f5958595e99c62126a74d32746a78/68747470733a2f2f706f7365722e707567782e6f72672f6b6c617564652f656c6f7175656e742d707265666572656e6365732f6c6963656e7365)](https://packagist.org/packages/klaude/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/klaude/eloquent-preferences/blob/master/CONTRIBUTING.md) for more information.

- [Installation](#installation)
    - [Configuring In Laravel](#configuring-in-laravel)
    - [Configuring Without Laravel](#configuring-without-laravel)
- [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 klaude/eloquent-preferences` to download and install the library.

### Configuring In Laravel

[](#configuring-in-laravel)

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

```
// ...

return [

    // ...

    'providers' => [

        // ...

        KLaude\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 KLaude\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();
    });
```

Usage
-----

[](#usage)

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

```
use KLaude\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 `KLaude\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 KLaude\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|KLaude\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';
```

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity35

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 91.7% 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 ~277 days

Recently: every ~732 days

Total

12

Last Release

739d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ee82ebeec5464001f1c8469ef26b140d0feb45af3c62ed0b60b1528d474a8461?d=identicon)[klaude](/maintainers/klaude)

---

Top Contributors

[![klaude](https://avatars.githubusercontent.com/u/45157?v=4)](https://github.com/klaude "klaude (44 commits)")[![mbalandis](https://avatars.githubusercontent.com/u/18264973?v=4)](https://github.com/mbalandis "mbalandis (2 commits)")[![FearStream](https://avatars.githubusercontent.com/u/54145207?v=4)](https://github.com/FearStream "FearStream (1 commits)")[![TheFrankman](https://avatars.githubusercontent.com/u/1402017?v=4)](https://github.com/TheFrankman "TheFrankman (1 commits)")

---

Tags

laraveleloquentpreferences

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[cviebrock/eloquent-sluggable

Easy creation of slugs for your Eloquent models in Laravel

4.0k13.6M253](/packages/cviebrock-eloquent-sluggable)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[watson/validating

Eloquent model validating trait.

9723.3M47](/packages/watson-validating)[cybercog/laravel-ban

Laravel Ban simplify blocking and banning Eloquent models.

1.1k651.8k11](/packages/cybercog-laravel-ban)[cybercog/laravel-love

Make Laravel Eloquent models reactable with any type of emotions in a minutes!

1.2k302.7k1](/packages/cybercog-laravel-love)[cviebrock/eloquent-taggable

Easy ability to tag your Eloquent models in Laravel.

567694.8k3](/packages/cviebrock-eloquent-taggable)

PHPackages © 2026

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