PHPackages                             serri/alchemist - 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. [Templating &amp; Views](/categories/templating)
4. /
5. serri/alchemist

ActiveLibrary[Templating &amp; Views](/categories/templating)

serri/alchemist
===============

The JSON Revolution for Laravel, a simple, fast, and elegant alternative to Laravel JSON Resource.

1.0.3(1y ago)89MITPHPPHP ^8.2

Since May 21Pushed 1y ago1 watchersCompare

[ Source](https://github.com/AdnanSerri/Alchemist)[ Packagist](https://packagist.org/packages/serri/alchemist)[ RSS](/packages/serri-alchemist/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (1)Versions (4)Used By (0)

🧙🏻‍♂️ Laravel Alchemist ⚗️
==========================

[](#‍️-laravel-alchemist-️)

[![Latest Version](https://camo.githubusercontent.com/991af4a99dcf6d40939922624234969fb9f45727fa77a14d76f56c96e019b3a1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73657272692f616c6368656d6973742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/serri/alchemist)[![License](https://camo.githubusercontent.com/961ce4a924242ef9f248523168b654e85b04215ca283c15e39c4f08de796c250/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f73657272692f616c6368656d6973742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/serri/alchemist)[![Total Downloads](https://camo.githubusercontent.com/e6f5e94594dd17db71b73a85ea5bd56dea5e4e30d902c95d0219e1dfb5bd736e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73657272692f616c6368656d6973742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/serri/alchemist)

### The JSON Revolution for Laravel, a simple, fast, and elegant alternative to Laravel JSON Resource.

[](#the-json-revolution-for-laravel-a-simple-fast-and-elegant-alternative-to-laravel-json-resource)

---

📖 Table of Contents
-------------------

[](#-table-of-contents)

1. [Philosophy](#philosophy)
2. [Requirements](#requirements)
3. [Installation](#installation)
4. [Fundamentals](#fundamentals)
5. [Quick Start](#quick-start)
6. [Usage &amp; Examples](#usage-examples)
7. [License](#license)

---

 🔮 Philosophy - The Problem with Traditional Laravel Resources
--------------------------------------------------------------------------------------------------

[](#--philosophy---the-problem-with-traditional-laravel-resources)

We've all been there:

- Creating endless resource classes that mostly repeat the same boilerplate.
- Duplicating code across multiple API responses.
- Drowning in maintenance when frontend requirements change.
- Wrestling with nested relationships that bloat your codebase.

The breaking point comes when:

- Your API evolves and resources multiply.
- Frontend devs request constant field changes.
- Your models grow, but your resource classes don't scale.
- Nested relationships turn into unmaintainable spaghetti.

The Solution: Laravel Alchemist - Formula Approach

**One File to Rule Them All**

Each model gets a single `SomeModelFormula.php` where you:

✅ Define all fields as simple strings in arrays.
✅ Manage every API variation in one place.
✅ Update database changes with a single edit.

**Relationship Handling Made Simple**

- Reference nested resources by their name only.
- Each relation maintains its own `Formula::class`.
- No more recursive resource nightmares.

**Frontend-Friendly Flexibility**

- Instantly modify fields without resource class hopping.
- Track all API variations through clear formula methods.
- Never miss a field update again.

**Why This Works**

- **Less Code:** Eliminates 80%+ of resource boilerplate.
- **True Maintainability:** All changes flow through controlled formulas.
- **Team Friendly:** Frontend can request changes without breaking your flow.

> *“Laravel Resources grant you the illusion of control – meticulous yet maddening. Laravel Alchemist surrenders this false dominion... and in its place conjures true magic.„*

---

 📋 Requirements
-----------------------------------------------------

[](#--requirements)

- PHP ≥ 8.2
- Laravel ≥ 11.x

---

 🔧 Installation
-----------------------------------------------------

[](#--installation)

You may install Alchemist using the Composer package manager:

```
  composer require serri/alchemist
```

You can publish the Alchemist configuration file `config/alchemist.php` and the default `Formulas/Formula.php` using `vendor:publish` Artisan command:

```
   php artisan vendor:publish --provider="Serri\Alchemist\AlchemistServiceProvider"
```

Or for configuration file using:

```
   php artisan vendor:publish --tag=alchemist-config
```

For default formula class using:

```
    php artisan vendor:publish --tag=alchemist-formula
```

---

 📖 Fundamentals
-----------------------------------------------------

[](#--fundamentals)

To wield this package's magic effectively, you must understand these arcane principles:

### **The Formulas Directory**

[](#the-formulas-directory)

- Your **sacred workshop** where all model formulas reside
- Created automatically at `app/Formulas/Formula.php` when you publish the default formula class as we did in the [Installtion](#installtion) Section:

```
namespace App\Formulas;

class Formula
{
    const BlankParchment = ['id']; # Default formula.
}
```

### Crafting Your Formulas

[](#crafting-your-formulas)

Begin your alchemy by creating formula classes in `app/Formulas/` like so:

```
namespace App\Formulas;

class UserFormula extends Formula
{
    # Define your transformations here.
    # ex:

    const UserLogin = ['id', 'username', /*...etc.*/]

    // ... other formulas.
}
```

> #### Key Laws:
>
> [](#key-laws)
>
> - #### Each model deserves its own formula class `ModelNameFormula.php`
>
>
>     [](#each-model-deserves-its-own-formula-class-modelnameformulaphp-)
> - #### The `BlankParchment` remains your fallback option.
>
>     [](#the-blankparchment-remains-your-fallback-option)

### Using package default Formula

[](#using-package-default-formula)

If you did not publish the `app/Formulas/Formula.php` , you can still use the default `Formula.php` provided by the package like this:

```
namespace App\Formulas;

use Serri\Alchemist\Formulas\Formula

class UserFormula extends Formula
{
    // Define your transformations here.
}
```

Relationships must be explicitly marked with the `#[Relation]` attribute to be available in formulas:

---

 🪄 Quick Start
---------------------------------------------------

[](#--quick-start)

### 1. Model Configuration

[](#1-model-configuration)

To enable formula support, models must use `HasAlchemyFormulas` Concern.

```
use Serri\Alchemist\Concerns\HasAlchemyFormulas;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasAlchemyFormulas;

    //
}
```

### 2. Exposing Fields

[](#2-exposing-fields)

By default, everything included in `$fillable` array and `$guarded` array are automatically loaded in formulas.

```
use Serri\Alchemist\Concerns\HasAlchemyFormulas;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasAlchemyFormulas;

    # Automatically exposed to formulas.
    protected $guarded = ['id'];

    # Automatically exposed to formulas.
    protected $fillable = [
        'title',
        'description',
        'published_at'
    ]
}
```

### 3. Exposing Relationships

[](#3-exposing-relationships)

Relationships must be explicitly marked with the `#[Relation]` decorator to be available in formulas:

```
use Serri\Alchemist\Decorators\Relation;

#[Relation] # Exposed to formulas as 'comments'
public function comments(): HasMany
{
    return $this->hasMany(Comment::class);
}

#[Relation(name: 'author_profile')] # Exposed to formulas as 'author_profile'
public function profile(): HasOne
{
    return $this->hasOne(Profile::class);
}
```

### 4. Exposing Custom Methods

[](#4-exposing-custom-methods)

Model methods require the `#[Mutagen]` decorator to be accessible in formulas:

```
use Serri\Alchemist\Decorators\Mutagen;

#[Mutagen] # Exposed to formulas as 'fullName'
public function fullName(): string
{
    return "{$this->first_name} {$this->last_name}";
}

#[Mutagen(name: 'is_verified')] # Exposed to formulas as 'is_verified'
public function isVerified(): bool
{
    return $this->email_verified_at !== null;
}
```

> #### Keynotes
>
> [](#keynotes)
>
> - #### `$fillable` / `$guarded` : are available to use in formulas by default.
>
>     [](#fillable--guarded--are-available-to-use-in-formulas-by-default)
> - #### **Decorators:** Only `#[Relation]` and `#[Mutagen]` methods are exposed to formulas.
>
>     [](#decorators-only-relation-and-mutagen-methods-are-exposed-to-formulas)

### 5. Crafting Formulas

[](#5-crafting-formulas)

Once your models are properly configured, you can define formulas to transform your data. Formulas are defined in classes within the `app/Formulas/` directory.

Here is an example:

```
namespace App\Formulas;

class PostFormula extends Formula
{
    const Author = ['id', 'title', 'author_profile'];

    const WithComments = ['id', 'title', 'comments']

    const Detailed = ['id', 'title', 'description', 'comments', 'author_profile']
}
```

For profile formula:

```
namespace App\Formulas;

class ProfileFormula extends Formula
{
    const OnlyName = ['fullName'];

    const AnyOther = ['id', 'username', 'fullName']
}
```

---

 🛠️ Usage &amp; Examples
----------------------------------------------------------------

[](#-️-usage--examples)

### Basic Data Transformation

[](#basic-data-transformation)

To transform model data using your formulas:

```
use App\Models\Post;
use App\Formulas\PostFormula;
use Serri\Alchemist\Facades\Alchemist;

// 1. Fetch your models
$posts = Post::with('author.profile')->get();

// 2. Specify which formulas to use
Post::setFormula(PostFormula::Author);
Profile::setFormula(ProfileFormula::OnlyName);

// 3. Process through Alchemist
$transformedData = Alchemist::brew($posts);
```

Results:

```
[
  [
    'id' => 1,
    'title' => "Post 1",
    'author_profile' => [
      'fullName' => "some author name"
    ]
  ],
  [
    'id' => 2,
    'title' => 'Post 2',
    'author_profile' => [
      'fullName' => "some author name"
    ]
  ],
  [
    'id' => 3,
    'title' => 'Post 3',
    'author_profile' => [
      'fullName' => "some author name"
    ]
  ]
]
```

### Key Methods

[](#key-methods)

MethodPurposeExample`setFormula()`Assigns formula variant`Post::setFormula(PostFormula::DetailedView)``brew()`Executes transformation`Alchemist::brew($collection|$model)``brewBatch()`Executes transformation`Alchemist::brewBatch($paginator)`### Patterns

[](#patterns)

#### 1. Context-Aware Formulas

[](#1-context-aware-formulas)

```
$formula = auth()->user()->isAdmin()
? PostFormula::AdminView
: PostFormula::PublicView;

Post::setFormula($formula);
```

#### 2. Direct Model Transformation

[](#2-direct-model-transformation)

```
$post = Post::find(1);
return Alchemist::brew($post); // Auto-detects single model
```

#### 3. Pagination Support

[](#3-pagination-support)

```
$paginated = Post::paginate(15);
return Alchemist::brewBatch($paginated); // Preserves pagination structure
```

### Syntax Variations

[](#syntax-variations)

#### 1. Helper Function (Simplest)

[](#1-helper-function-simplest)

```
$posts = Post::all();
$transformed = alchemist()->brew($posts);
```

#### 2. Facade (For static contexts)

[](#2-facade-for-static-contexts)

```
use Serri\Alchemist\Facades\Alchemist;

$data = Alchemist::brew($models);
```

#### 3. Dependency Injection (Recommended for controllers)

[](#3-dependency-injection-recommended-for-controllers)

```
use Serri\Alchemist\Services\Alchemist;

class PostController
{
public function __construct(
    protected Alchemist $alchemist
) {}

    public function index()
    {
        return $this->alchemist->brew(Post::all());
    }
}
```

---

 📜 License
--------------------------------------------

[](#--license)

This project is open-source and available under the **MIT License**.

###  Health Score

31

—

LowBetter than 66% of packages

Maintenance46

Moderate activity, may be stable

Popularity10

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 66.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 ~0 days

Total

3

Last Release

408d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/58080657?v=4)[AdnanSerri](/maintainers/AdnanSerri)[@AdnanSerri](https://github.com/AdnanSerri)

---

Top Contributors

[![lumbermj](https://avatars.githubusercontent.com/u/110980468?v=4)](https://github.com/lumbermj "lumbermj (12 commits)")[![AdnanSerri](https://avatars.githubusercontent.com/u/58080657?v=4)](https://github.com/AdnanSerri "AdnanSerri (6 commits)")

---

Tags

arrayarray-manipulationsexportjsonjson-apijson-resourceslaravellaravel-packagephp-libraryphp8resource

### Embed Badge

![Health badge](/badges/serri-alchemist/health.svg)

```
[![Health](https://phpackages.com/badges/serri-alchemist/health.svg)](https://phpackages.com/packages/serri-alchemist)
```

###  Alternatives

[limenius/react-bundle

Client and Server-side react rendering in a Symfony Bundle

3851.2M](/packages/limenius-react-bundle)[area17/laravel-auto-head-tags

Laravel Auto Head Tags helps you build the list of head elements for your app

4616.1k](/packages/area17-laravel-auto-head-tags)[jelix/wikirenderer

WikiRenderer is a library to generate HTML or anything else from wiki content.

1712.3k1](/packages/jelix-wikirenderer)[webkinder/sproutset

A Composer package for handling responsive images in Roots Bedrock + Sage + Blade projects.

282.2k](/packages/webkinder-sproutset)[muratbsts/mail-template

This package is a easy to use mail template collection for Laravel 5.x.

191.3k](/packages/muratbsts-mail-template)

PHPackages © 2026

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