PHPackages                             brandonkerr/eloquent-from-settings - 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. brandonkerr/eloquent-from-settings

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

brandonkerr/eloquent-from-settings
==================================

Easily generate eloquent models and relationships from JSON or array

1.0.0(3y ago)010MITPHPPHP ^8.1

Since Apr 8Pushed 3y ago1 watchersCompare

[ Source](https://github.com/BrandonKerr/eloquent-from-settings)[ Packagist](https://packagist.org/packages/brandonkerr/eloquent-from-settings)[ RSS](/packages/brandonkerr-eloquent-from-settings/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (6)Versions (4)Used By (0)

Eloquent From Settings
======================

[](#eloquent-from-settings)

[![Packagist Version](https://camo.githubusercontent.com/c6f63a31afef3be32dd8c16184295d6befe146f0e07fbf96557869ced7e8126d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f4272616e646f6e4b6572722f656c6f7175656e742d66726f6d2d73657474696e6773)](https://packagist.org/packages/brandonkerr/eloquent-from-settings)[![Tests](https://github.com/BrandonKerr/eloquent-from-settings/actions/workflows/test.yml/badge.svg)](https://github.com/BrandonKerr/eloquent-from-settings/actions/workflows/test.yml)[![Static Analysis](https://github.com/BrandonKerr/eloquent-from-settings/actions/workflows/static-analysis.yml/badge.svg)](https://github.com/BrandonKerr/eloquent-from-settings/actions/workflows/static-analysis.yml)[![codecov](https://camo.githubusercontent.com/ac95e92fdcc7f408e28de782465779287acaae8c0792765d161df1375a8cd087/68747470733a2f2f636f6465636f762e696f2f67682f4272616e646f6e4b6572722f656c6f7175656e742d66726f6d2d73657474696e67732f6272616e63682f6d61696e2f67726170682f62616467652e7376673f746f6b656e3d36494c38305147334c4b)](https://codecov.io/gh/BrandonKerr/eloquent-from-settings)

This package allows you to easily build Eloquent models and their relationships, through data settings via array or JSON passed to the model's factory.

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

[](#installation)

Install the package via composer:

```
composer require brandonkerr/eloquent-from-settings
```

First, ensure that your model has a factory:

```
namespace App\Models;

// ...
use Illuminate\Database\Eloquent\Factories\HasFactory;

class User extends Authenticatable
{
    use HasFactory;
    // ...
}
```

Then simply add the `FromSettings` trait to your factory:

```
namespace Database\Factories;

// ...
use Brandonkerr\EloquentFromSettings\Traits\FromSettings;

class UserFactory extends Factory
{
    use FromSettings;
    // ...
}
```

Configuration
-------------

[](#configuration)

By default, the `FromSettings` trait behaves strictly and will throw:

- a `MissingTraitException` if a keyed relationship does not use the FromSettings trait
- an `UnknownKeyException` if a key cannot be matched to an attribute, relationship, or function

While this is the recommended behaviour to ensure data integrity, you have the freedom to change these settings.

If you would like to allow for a keyed relationship that **does not** use the FromSettings trait, you can either set the `$throwsMissingTraitException` property to false:

```
class FooFactory extends Factory
{
    use FromSettings;

    public bool $throwsMissingTraitException = false;

    // ...
}
```

or for a customized logic, implement `FromSettingsInterface` and complete the `getThrowsMissingTraitException()` function:

```
class BarFactory extends Factory implements FromSettingsInterface
{
    use FromSettings;

    public function getThrowsMissingTraitException(): bool
    {
        return $this->someCustomSettingOrLogic;
    }

    // ...
}
```

If you would like to allow for unknown keys to be silently dropped, you can either set the `$throwsUnknownKeyException`property to false:

```
class FooFactory extends Factory
{
    use FromSettings;

    public bool $throwsUnknownKeyException = false;

    // ...
}
```

or for a customized logic, implement `FromSettingsInterface` and complete the `getThrowsUnknownKeyException()` function:

```
class BarFactory extends Factory implements FromSettingsInterface
{
    use FromSettings;

    public function getThrowsUnknownKeyException(): bool
    {
        return $this->someCustomSettingOrLogic;
    }

    // ...
}
```

Usage
-----

[](#usage)

Simply pass the desired settings via array to the factor's `fromSettingsArray` function:

```
$data = [
        "name" => "Brandon Kerr",
        "books" => [
            [
                "title" => "How to Use Eloquent From Settings",
                "reviews" => [
                    [
                        "reviewer" => "Jane Doe",
                        "score" => 80,
                    ],
                    [
                        "reviewer" => "John Smith",
                        "score" => 45,
                    ],
                ],
            ],
        ],
    ];
Author::factory()->fromSettingsArray(...$data)->create();
```

or via JSON to the factor's `fromSettingsJson` function:

```
$json = '{
   "name":"Brandon Kerr",
   "books":[
      {
         "title":"How to Use Eloquent From Settings",
         "reviews":[
            {
               "reviewer":"Jane Doe",
               "score":80
            },
            {
               "reviewer":"John Smith",
               "score":45
            }
         ]
      }
   ]
}';
Author::factory()->fromSettingsJson($json)->create();
```

The end result will be

- an Author model with name *Brandon Kerr*
- a Book model whose Author is created above and title is *How to Use Eloquent From Settings*
- a Review for the Book created above with reviewer *Jane Doe* and a score of *80*
- a Review for the Book created above with reviewer *John Smith* and a score of *45*

Full Example
------------

[](#full-example)

This example covers Authors writing Books, which have Reviews. Full details can be found in the tests directory of this package.

### Models and Schemas

[](#models-and-schemas)

Refer to the Models and Migrations directories under tests/Stubs for full details.

#### Author

[](#author)

Column/AttributeTypeNotesidunsigned bigintPrimary Keynamestringunique constraint added for use in a custom function test- an Author `HasMany` Books
- an Author `HasManyThrough` Reviews (through Books)

#### Book

[](#book)

Column/AttributeTypeNotesidunsigned bigintPrimary Keytitlestringtitle of the bookauthor\_idunsigned bigintForeign Key to Author- a Book `BelongsTo` an Author
- a Book `HasMany` Reviews

#### Review

[](#review)

Column/AttributeTypeNotesidunsigned bigintPrimary Keyreviewerstringname of the reviewerscoreintegerthe score (out of 100)book\_idunsigned bigintForeign Key to Book- a Review `BelongsTo` a Book

### Factories

[](#factories)

The `AuthorFactory` and `ReviewFactory` classes are completely standard (aside from using the `FromSettings` trait), but the `BookFactory` has two custom functions to showcase additional functionality of this package:

```
 /**
 * Custom function to find or create the author, based on the given name
 *
 * @param string $name
 * @return $this
 */
public function forAuthor(string $name): self
{
    $author = Author::firstOrCreate([
        "name" => $name
    ]);

    return $this->state(["author_id" => $author->id]);
}

/**
 * Custom function to add reviews with a perfect score
 *
 * @param string ...$names
 * @return $this
 */
public function perfectReviews(string ...$names): self
{
    return $this->has(
        Review::factory()
            ->count(count($names))
            ->sequence(fn (Sequence $sequence) => [
                "reviewer" => $names[$sequence->index],
                "score" => 100,
            ])
    );
}
```

### Settings Data

[](#settings-data)

Below is a commented example of an array of settings, where the author is the root of the data:

```
$data = [
        // the author's name attribute
        "name" => "Bob",
        // the author's HasMany relationship with Book
        "books" => [
            // first book
            [
                // the book's title attribute
                "title" => "Bob's First Book",
                // the book's HasMany relationship with Review
                "reviews" => [
                    // first review
                    [
                        // the review's reviewer attribute
                        "reviewer" => "Jane Doe",
                        // the review's score attribute
                        "score" => 80,
                    ],
                    // second review
                    [
                        // the review's reviewer attribute
                        "reviewer" => "John Smith",
                        // the review's score attribute
                        "score" => 45,
                    ],
                ],
            ],
            // second book
            [
                // the book's title attribute
                "title" => "Please Don't Review Me",
                // NOTE no reviews
            ],
        ],
    ];
```

Then we simply call the Author's factory:

```
$author = Author::factory()->fromSettingsArray(...$data)->create();
```

The end result is

- One Author with name *Bob*, which has two books:
    - The first book is titled *Bob's First Book* and has two reviews:
        - one with reviewer *Jane Doe* and a score of *80*, and
        - one with reviewer *John Smith* and a score of *45*.
    - The second book is titled *Please Don't Review Me* and has zero reviews.

#### BelongsTo

[](#belongsto)

We aren't limited to Has\_\_ relationships, like in the example above. We can also use a Book as the data root, and create an author for it:

```
$data = [
    "title" => "My Book",
    "author" => [
        "name" => "Bob Jones",
    ],
];
Book::factory()->fromSettingsArray(...$data)->create();
```

The end result is one Author named *Bob Jones*, which has one Book titled *My Book*.

#### Custom Functions

[](#custom-functions)

But what if we don't want to create a new author, and don't know the author's ID that we could use to set the book's author\_id value? You could create a custom function on the Book's factory that can find the author by their name, and assign the author to the book. See the `forAuthor()` function above for details.

```
Author::create([
    "name" => "Bob Jones"
]);
// ...
$data = [
    "title" => "My Book",
    "forAuthor" => [
        "name" => "Bob Jones",
    ],
];

$book = Book::factory()->fromSettingsArray(...$data)->create();
```

The end result is again one Author named *Bob Jones*, which has one Book titled *My Book*, but since the Author named *Bob Jones* already existed, it would not be created again, and it would not violate our unique name constraint on the Authors table.

We can also use a custom function to accept non key-value pair settings. See the `perfectReviews()` function above for details.

```
$data = [
    "title" => "My Book",
    "author" => [
        "name" => "Bob Jones",
    ],
    "perfectReviews" => [
        [
            "Jane Doe",
        ],
        [
            "John Smith",
        ],
    ],
];
```

The end result is once again one Author named *Bob Jones*, which has one Book titled *My Book*. However, this time the Book has two Reviews: one with reviewer *Jane Doe*, and the other with reviewer *John Smith*, and both with a score of *100* (as set by the `perfectReviews` function).

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~9 days

Total

2

Last Release

1121d ago

Major Versions

0.1.0 → 1.0.02023-04-17

### Community

Maintainers

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

---

Top Contributors

[![BrandonKerr](https://avatars.githubusercontent.com/u/1359518?v=4)](https://github.com/BrandonKerr "BrandonKerr (10 commits)")

---

Tags

laravelfactorySettingsdatabaseeloquent

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/brandonkerr-eloquent-from-settings/health.svg)

```
[![Health](https://phpackages.com/badges/brandonkerr-eloquent-from-settings/health.svg)](https://phpackages.com/packages/brandonkerr-eloquent-from-settings)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[pdphilip/elasticsearch

An Elasticsearch implementation of Laravel's Eloquent ORM

145360.2k4](/packages/pdphilip-elasticsearch)[toponepercent/baum

Baum is an implementation of the Nested Set pattern for Eloquent models.

3154.7k](/packages/toponepercent-baum)[czim/laravel-filter

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

8973.0k3](/packages/czim-laravel-filter)[eusonlito/laravel-database-cache

Cache Database Query results on Laravel Query Builder or Eloquent

194.2k](/packages/eusonlito-laravel-database-cache)

PHPackages © 2026

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