PHPackages                             fuzz/magic-box - 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. fuzz/magic-box

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

fuzz/magic-box
==============

A magical implementation of Laravel's Eloquent models as injectable, masked resource repositories.

1.1.2(9y ago)4627.2k4[1 issues](https://github.com/fuzz-productions/magic-box/issues)2MITPHP

Since Jul 15Pushed 3y agoCompare

[ Source](https://github.com/fuzz-productions/magic-box)[ Packagist](https://packagist.org/packages/fuzz/magic-box)[ Docs](https://fuzzproductions.com/)[ RSS](/packages/fuzz-magic-box/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependencies (4)Versions (14)Used By (2)

Laravel Magic Box
=================

[](#laravel-magic-box)

⛔️ DEPRECATED ⛔️
================

[](#️-deprecated-️)

*This project is no longer supported or maintained. If you need a modern version of Magic Box that is compatible with newer versions of Laravel please consider using the spiritual successor to this project — [Koala Pouch](https://github.com/koala-labs/pouch).*

---

Magic Box modularizes Fuzz's magical implementation of Laravel's Eloquent models as injectable, masked resource repositories.

##### Magic Box has two goals:

[](#magic-box-has-two-goals)

1. To create a two-way interchange format, so that the JSON representations of models broadcast by APIs can be re-applied back to their originating models for updating existing resources and creating new resources.
2. Provide an interface for API clients to request exactly the data they want in the way they want.

Installation/Setup
------------------

[](#installationsetup)

1. `composer require fuzz/magic-box`
2. Use or extend `Fuzz\MagicBox\Middleware\RepositoryMiddleware` into your project and register your class under the `$routeMiddleware` array in `app/Http/Kernel.php`. `RepositoryMiddleware` contains a variety of configuration options that can be overridden
3. If you're using `fuzz/api-server`, you can use magical routing by updating `app/Providers/RouteServiceProvider.php`, `RouteServiceProvider@map`, to include:

    ```
    /**
     * Define the routes for the application.
     *
     * @param  \Illuminate\Routing\Router $router
     * @return void
     */
    public function map(Router $router)
    {
        // Register a handy macro for registering resource routes
        $router->macro('restful', function ($model_name, $resource_controller = 'ResourceController') use ($router) {
            $alias = Str::lower(Str::snake(Str::plural(class_basename($model_name)), '-'));

            $router->resource($alias, $resource_controller, [
                'only' => [
                    'index',
                    'store',
                    'show',
                    'update',
                    'destroy',
                ],
            ]);
        });

        $router->group(['namespace' => $this->namespace], function ($router) {
            require app_path('Http/routes.php');
        });
    }
    ```
4. Set up your MagicBox resource routes under the middleware key you assign to your chosen `RepositoryMiddleware` class
5. Set up a `YourAppNamespace\Http\Controllers\ResourceController`, [here is what a ResourceController might look like](https://gist.github.com/SimantovYousoufov/dea19adb1dfd8f05c1fcad9db976c247) .
6. Set up models according to `Model Setup` section

Testing
-------

[](#testing)

Just run `phpunit` after you `composer install`.

Eloquent Repository
-------------------

[](#eloquent-repository)

`Fuzz\MagicBox\EloquentRepository` implements a CRUD repository that cascades through relationships, whether or not related models have been created yet.

Consider a simple model where a User has many Posts. EloquentRepository's basic usage is as follows:

Create a User with the username Steve who has a single Post with the title Stuff.

```
$repository = (new EloquentRepository)
    ->setModelClass('User')
    ->setInput([
        'username' => 'steve',
        'nonsense' => 'tomfoolery',
        'posts'    => [
            'title' => 'Stuff',
        ],
    ]);

$user = $repository->save();
```

When `$repository->save()` is invoked, a User will be created with the username "Steve", and a Post will be created with the `user_id` belonging to that User. The nonsensical "nonsense" property is simply ignored, because it does not actually exist on the table storing Users.

By itself, EloquentRepository is a blunt weapon with no access controls that should be avoided in any public APIs. It will clobber every relationship it touches without prejudice. For example, the following is a BAD way to add a new Post for the user we just created.

```
$repository
    ->setInput([
        'id' => $user->id,
        'posts'    => [
            ['title' => 'More Stuff'],
        ],
    ])
    ->save();
```

This will delete poor Steve's first post—not the intended effect. The safe(r) way to append a Post would be either of the following:

```
$repository
    ->setInput([
        'id' => $user->id,
        'posts'    => [
            ['id' => $user->posts->first()->id],
            ['title' => 'More Stuff'],
        ],
    ])
    ->save();
```

```
$post = $repository
    ->setModelClass('Post')
    ->setInput([
        'title' => 'More Stuff',
        'user' => [
            'id' => $user->id,
        ],
    ])
    ->save();
```

Generally speaking, the latter is preferred and is less likely to explode in your face.

The public API methods that return models from a repository are:

1. `create`
2. `read`
3. `update`
4. `delete`
5. `save`, which will either call `create` or `update` depending on the state of its input
6. `find`, which will find a model by ID
7. `findOrFail`, which will find a model by ID or throw `\Illuminate\Database\Eloquent\ModelNotFoundException`

The public API methods that return an `\Illuminate\Database\Eloquent\Collection` are:

1. `all`

Filtering
---------

[](#filtering)

`Fuzz\MagicBox\Filter` handles Eloquent Query Builder modifications based on filter values passed through the `filters`parameter.

Tokens and usage:

TokenDescriptionExample`^`Field starts with`https://api.yourdomain.com/1.0/users?filters[name]=^John``$`Field ends with`https://api.yourdomain.com/1.0/users?filters[name]=$Smith``~`Field contains`https://api.yourdomain.com/1.0/users?filters[favorite_cheese]=~cheddar``50``>=`Field is greater than or equals`https://api.yourdomain.com/1.0/users?filters[lifetime_value]=>=50`` 'Bobby',
    'profile' => [
        'hobbies' => [
            ['name' => 'Hockey'],
            ['name' => 'Programming'],
            ['name' => 'Cooking']
        ]
    ]
]
```

We can filter by users' hobbies with `users?filters[profile.hobbies.name]=^Cook`. Relationships can be of arbitrary depth.

### Filter conjuctions

[](#filter-conjuctions)

We can use `AND` and `OR` statements to build filters such as `users?filters[username]==Bobby&filters[or][username]==Johnny&filters[and][profile.favorite_cheese]==Gouda`. The PHP array that's built from this filter is:

```
[
    'username' => '=Bobby',
    'or'       => [
          'username' => '=Johnny',
          'and'      => [
              'profile.favorite_cheese' => '=Gouda',
          ]
    ]
]
```

and this filter can be read as `select (users with username Bobby) OR (users with username Johnny who's profile.favorite_cheese attribute is Gouda)`.

Model Setup
-----------

[](#model-setup)

Models need to implement `Fuzz\MagicBox\Contracts\MagicBoxResource` before MagicBox will allow them to be exposed as a MagicBox resource. This is done so exposure is an explicit process and no more is exposed than is needed.

Models also need to define their own `$fillable` array including attributes and relations that can be filled through this model. For example, if a User has many posts and has many comments but an API consumer should only be able to update comments through a user, the `$fillable` array would look like:

```
protected $fillable = ['username', 'password', 'name', 'comments'];

```

MagicBox will only modify attributes/relations that are explicitly defined.

Resolving models
----------------

[](#resolving-models)

Magic Box is great and all, but we don't want to resolve model classes ourselves before we can instantiate a repository...

If you've configured a RESTful URI structure with pluralized resources (i.e. `https://api.mydowmain.com/1.0/users` maps to the User model), you can use `Fuzz\MagicBox\Utility\Modeler` to resolve a model class name from a route name.

Testing
-------

[](#testing-1)

`phpunit` :)

### TODO

[](#todo)

1. Route service provider should be pre-setup
2. Support more relationships (esp. polymorphic relations) through cascading saves.
3. Support paginating nested relations

###  Health Score

39

—

LowBetter than 85% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity33

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity70

Established project with proven stability

 Bus Factor1

Top contributor holds 58.2% 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 ~392 days

Recently: every ~552 days

Total

7

Last Release

1360d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/00415e4fac75ee392fb49e37fb7fb412b908687d4da0eb3ff0e942c944d619c9?d=identicon)[Fuzzpro](/maintainers/Fuzzpro)

---

Top Contributors

[![stristr](https://avatars.githubusercontent.com/u/1203925?v=4)](https://github.com/stristr "stristr (39 commits)")[![SimantovYousoufov](https://avatars.githubusercontent.com/u/8379657?v=4)](https://github.com/SimantovYousoufov "SimantovYousoufov (15 commits)")[![maidoesthings](https://avatars.githubusercontent.com/u/7562272?v=4)](https://github.com/maidoesthings "maidoesthings (7 commits)")[![kfuchs](https://avatars.githubusercontent.com/u/2237033?v=4)](https://github.com/kfuchs "kfuchs (3 commits)")[![fuzzjham](https://avatars.githubusercontent.com/u/44976067?v=4)](https://github.com/fuzzjham "fuzzjham (2 commits)")[![walterbm](https://avatars.githubusercontent.com/u/7892079?v=4)](https://github.com/walterbm "walterbm (1 commits)")

---

Tags

api-frameworklaravel-5-packagelaravel-eloquent-models

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/fuzz-magic-box/health.svg)

```
[![Health](https://phpackages.com/badges/fuzz-magic-box/health.svg)](https://phpackages.com/packages/fuzz-magic-box)
```

###  Alternatives

[spatie/laravel-medialibrary

Associate files with Eloquent models

6.1k43.2M623](/packages/spatie-laravel-medialibrary)[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.4M93](/packages/mongodb-laravel-mongodb)[kirschbaum-development/eloquent-power-joins

The Laravel magic applied to joins.

1.6k32.6M45](/packages/kirschbaum-development-eloquent-power-joins)[owen-it/laravel-auditing

Audit changes of your Eloquent models in Laravel

3.4k36.8M150](/packages/owen-it-laravel-auditing)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8793.2M24](/packages/yajra-laravel-oci8)[awobaz/compoships

Laravel relationships with support for composite/multiple keys

1.2k11.7M46](/packages/awobaz-compoships)

PHPackages © 2026

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