PHPackages                             kouks/laravel-casters - 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. [API Development](/categories/api)
4. /
5. kouks/laravel-casters

ActiveLibrary[API Development](/categories/api)

kouks/laravel-casters
=====================

Provides a convenient way to cast and transform your models for API purposes.

1.1.0(9y ago)1150[3 issues](https://github.com/kouks/laravel-casters/issues)MITPHPPHP &gt;=5.6.4

Since Nov 7Pushed 9y ago1 watchersCompare

[ Source](https://github.com/kouks/laravel-casters)[ Packagist](https://packagist.org/packages/kouks/laravel-casters)[ RSS](/packages/kouks-laravel-casters/feed)WikiDiscussions master Synced 4w ago

READMEChangelog (3)Dependencies (3)Versions (5)Used By (0)

Laravel Casters
===============

[](#laravel-casters)

[![Scrutinizer Code Quality](https://camo.githubusercontent.com/cf6507431bb0f0ca98af86d38966fd5f37d3c2c45e8f81b9317a58ce1fe85c2f/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6b6f756b732f6c61726176656c2d636173746572732f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/kouks/laravel-casters/?branch=master)[![Latest Version on Packagist](https://camo.githubusercontent.com/724d0597f87acf5c29915a09ce05684a3fec3965d17d2207d52a4f062ce3d9c6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6b6f756b732f6c61726176656c2d636173746572732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/kouks/laravel-casters)[![Build Status](https://camo.githubusercontent.com/b0b877632a9db4452df9f17846381080bd22d03fcdc39d76f845d1d9a4b5c703/68747470733a2f2f7472617669732d63692e6f72672f6b6f756b732f6c61726176656c2d636173746572732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/kouks/laravel-casters)[![StyleCI](https://camo.githubusercontent.com/02532de4294d5b771ee10bfdaabe022d94434c872d5509e79a2890b1ad7138f2/68747470733a2f2f7374796c6563692e696f2f7265706f732f37333032313731312f736869656c643f6272616e63683d6d6173746572)](https://styleci.io/repos/73021711)

Contents
--------

[](#contents)

- [Installation](#installation)
- [Usage](#usage)
- [FAQ](#faq)

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

[](#installation)

### Composer

[](#composer)

Open your console and `cd` into your Laravel project. Run:

```
composer require kouks/laravel-casters
```

Yeah, you are pretty much ready to go right now...

Usage
-----

[](#usage)

### Creating casters

[](#creating-casters)

You can put you casters pretty much anywhere, but I suppose you put them in a `app/Casters` directory. Now make a new php class, we are gonna be casting a Post model here. **Suppose our model has only `id`, `title`, `body` and `active` database columns, along with timestamps.**

```
namespace App\Casters;

use Koch\Casters\Caster;

class PostCaster extends Caster
{
    //
}
```

Good! Now we can put in our first casting rule.

```
namespace App\Casters;

use Koch\Casters\Caster;

class PostCaster extends Caster
{
    public castRules()
    {
        return [
            'title',
        ];
    }
}
```

This caster is going to cast only the title column, leaving its contents unchanged. More about making rules in the follwing section.

### Making your rules

[](#making-your-rules)

Let's move on how to make your own rules, there are **four** ways to achieve that at this moment.

**Simple casting/renaming columns**

There was an example of a simple cast rule in the previous section. Let us reviews it again and att something up.

```
namespace App\Casters;

use Koch\Casters\Caster;

class PostCaster extends Caster
{
    public castRules()
    {
        return [
            'title',
            'body' => 'long_text',
        ];
    }
}
```

This rule will remain the `title` column unchanged completely, and renaming the `body` column to `long_text`, however **leaving the contents unchanged**.

**Using cast queries**

Similar to Laravel's validation rules, you can use queries to cast.

```
namespace App\Casters;

use Koch\Casters\Caster;

class PostCaster extends Caster
{
    public castRules()
    {
        return [
            'active' => '!name:is_active|type:bool',
        ];
    }
}
```

Note the `!` before the cast rule. This says that we want to use a query. This simple query renames the `active` column to `is_active` and casts its contents to a boolean. All documentation on cast queries can be found in the [Cast queries](#cast-queries) section.

**Casting using a closure**

As a value of the cast rules, you can speficy a closure, which will determine what data to return.

```
namespace App\Casters;

use App\Post;
use Koch\Casters\Caster;

class PostCaster extends Caster
{
    public castRules()
    {
        return [
            'text' => function (Post $post) {
                return str_limit($post->body, 100);
            },
        ];
    }
}
```

This particular query is going to cast a **new** column `body` and as its contents it is going to use whatever is returned from the closure. In this case - the post body limited to 100 characters. Note that **you are given an instance of the model** that is being cast in the closure arguments.

**Casting using a method**

You can even use other methods on the caster class to determine what is going to be cast.

```
namespace App\Casters;

use App\Post;
use Koch\Casters\Caster;

class PostCaster extends Caster
{
    public castRules()
    {
        return [
            'draft' => '@isDraft',
        ];
    }

    public function isDraft(Post $post)
    {
        return ! $post->active;
    }
}
```

Notice the `@` sign - it is to determine that we want to use a caster class method to do the casting. This cast is (similarly to the closure one) create a new column `draft`, which is just a negation of the `active` column in this example. You are given the model instance in this case, too.

### Actual casting

[](#actual-casting)

The actual casting gets really simple, there are two ways to cast you data at this moment.

**Casting a single model**

Let us have a controller action `show`, which is going to cast our model, and retrun it as json.

```
...

class PostController extends Controller
{
    public function show(Post $post, PostCaster $caster)
    {
        return $caster->cast($post);
    }
}
```

Note that you can use *DI* for your casters, as with anything in Laravel. Then you call a single `cast` method and provide you model instance in the arguments. **If we were to combine all the example casters**, the returned json could look following:

```
{
  "id": 1,
  "title": "Some title",
  "long_text": "Some long text...",
  "text": "Some long text...",
  "active": true,
  "draft": false,
  "updated_at": {
    "date": "2016-11-01 00:38:03.000000",
    "timezone_type": 3,
    "timezone": "UTC"
  },
  "created_at": {
    "date": "2016-08-06 17:58:09.000000",
    "timezone_type": 3,
    "timezone": "UTC"
  }
}
```

*Note that in the example above, the `text` field is going to be limited to 100 characters.*

**Casting a collection**

You cast collections in **the same way** that you would cast single models. Only difference is that you are given back array of cast models, instead of a single one.

**Casting directly from model instance**

This package provides the `Koch\Casters\Behavior\Castable` trait, which lets you do **both** casting a single model as follows:

```
$post->cast($caster);
```

**and** a collection directly from you query:

```
Post::cast($caster);
```

**Also note that if you specify a full class path to the caster in you model, you can omit the `caster` variable completely.**

```
...
class Post extends Model
{
    use Castable;

    protected $caster = App\Casters\PostCaster::class;
}
```

Lets you do this fancy stuff:

```
$post->cast();

Post::cast();
```

If you follow the convention of storing your casters in the `app/Casters` directory as well as the naming conventions, this package will try to find related caster in that location - this lets you leave out even the `caster` property.

### Casting relationships

[](#casting-relationships)

There, obviously, is a way to cast relationships. Suppose there is a related model `Comments`, wich has a `many-one` relationship with our `Post` model. Also suppose that there is a `CommentCaster` set up. Look at the following code:

```
namespace App\Casters;

use App\Post;
use Koch\Casters\Caster;

class PostCaster extends Caster
{
    protected $commentCaster;

    public function __construct(CommentCaster $commentCaster)
    {
        $this->commentCaster = $commentCaster;
    }

    public castRules()
    {
        return [
            'comments' => function (Post $post) {
                return $this->commentCaster->cast($post->comments);
            },
        ];
    }
}
```

Note that even here you can levarage Laravel's *DI*. You now create a new column `comments`, which is then populated by the closure. This closure usis the injected caster to cast the comments relationship. You can do the same with casting via methods.

**Also beware of cycling your casts. At the moment, there is no check for that. So if you were to cast your `comments` relationship on the `PostCaster` and do the same vice versa, you'd end end with a 500.** Feel free to submit a PR correcting this issue.

### Cast queries

[](#cast-queries)

At this moment, there are only two queries. I am open for suggestions to add more.

- **`name:new_name`**
- **`type:new_type`** - accepts `int`, `string`, `bool` and `float`

### Abstracion

[](#abstracion)

There is a `Koch\Casters\Contracts\Caster` interface, which you could use for example with the repository pattern, where you have a parent `Repository` class which deals with all the stuff around any model, including casting it. You might want to inject the caster though a `PostRepository` constructor, in which case, the parent class would require the contract.

FAQ
---

[](#faq)

Nobody has ever asked me anything about this package so I can't determine the frequency of questions.

###  Health Score

23

—

LowBetter than 26% of packages

Maintenance0

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity61

Established project with proven stability

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

Total

3

Last Release

3522d ago

Major Versions

0.0.1 → 1.0.02016-11-07

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3684840?v=4)[Pavel Koch](/maintainers/kouks)[@kouks](https://github.com/kouks)

---

Top Contributors

[![kouks](https://avatars.githubusercontent.com/u/3684840?v=4)](https://github.com/kouks "kouks (12 commits)")

---

Tags

apilaraveltransformcasters

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/kouks-laravel-casters/health.svg)

```
[![Health](https://phpackages.com/badges/kouks-laravel-casters/health.svg)](https://phpackages.com/packages/kouks-laravel-casters)
```

###  Alternatives

[spatie/laravel-fractal

An easy to use Fractal integration for Laravel applications

1.9k15.7M112](/packages/spatie-laravel-fractal)[essa/api-tool-kit

set of tools to build an api with laravel

53386.5k](/packages/essa-api-tool-kit)[api-platform/laravel

API Platform support for Laravel

59156.3k11](/packages/api-platform-laravel)[simplestats-io/laravel-client

Analytics for Laravel. Track visitors, registrations, and payments. Discover which channels actually drive revenue, not just traffic. Server-side, GDPR compliant, ad-blocker proof.

5019.3k](/packages/simplestats-io-laravel-client)

PHPackages © 2026

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