PHPackages                             cviebrock/eloquent-typecast - 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. cviebrock/eloquent-typecast

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

cviebrock/eloquent-typecast
===========================

Trait for Eloquent models to force type-casting on retrieved values

1.0.2(11y ago)2468.0k↓43.3%1MITPHPPHP &gt;=5.4.0

Since Jul 12Pushed 10y ago4 watchersCompare

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

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

EloquentTypecast
================

[](#eloquenttypecast)

A trait that allows a Laravel project's Eloquent models to cast attribute values to native PHP variable types.

[![Latest Stable Version](https://camo.githubusercontent.com/51245cbaede970a9337ec7f3539aa31c12aa4ce0070b4ecac809cd8862bec10a/68747470733a2f2f706f7365722e707567782e6f72672f6376696562726f636b2f656c6f7175656e742d74797065636173742f762f737461626c652e706e67)](https://packagist.org/packages/cviebrock/eloquent-typecast)[![Total Downloads](https://camo.githubusercontent.com/ee1e6d34887fe35bc24e87f4af43e4002ad601c465190e1119419e1ea08f6de8/68747470733a2f2f706f7365722e707567782e6f72672f6376696562726f636b2f656c6f7175656e742d74797065636173742f646f776e6c6f6164732e706e67)](https://packagist.org/packages/cviebrock/eloquent-typecast)

- [Background](#background)
- [Installation and Requirements](#installation)
- [Usage](#usage)
- [Notes](#notes)
- [Bugs, Suggestions and Contributions](#bugs)
- [Copyright and License](#copyright)

---

Background: Why Do I Need This?
-------------------------------

[](#background-why-do-i-need-this)

For some database drivers, all the attributes you get back from a query are returned as strings, even when the underlaying column-type is *INTEGER* or *FLOAT* or *BOOLEAN*.

Rather than have to use these "integer-looking" strings, etc., and rely on PHP's type-juggling, this trait will cast those attribute values to the proper native PHP variable type automagically for you.

This is also going to be very handy if you are, say, building an API and would like to just return JSON-versions of Eloquent models. Using this trait, all the JSON elements are going to be the right type for consumers of your API -- instead of all strings -- saving them type-juggling on their end.

> Note: I believe if you are using the mysqlnd drivers in your PHP installation, then you don't need this trait as mysqlnd handles this type casting for you. Try it out by doing a `var_dump($model->getKey())`. If it shows that the value is an integer, you don't need this package. If it shows it's a string, read on.

Installation &amp; Requirements
-------------------------------

[](#installation--requirements)

In your project's composer.json file:

```
"require": {
    "cviebrock/eloquent-typecast": "1.*"
}
```

In your project's models (or your own base model):

```
use Cviebrock\EloquentTypecast\EloquentTypecastTrait;

class MyModel {

    use EloquentTypecastTrait;

    // Define the attributes you want typecast here
    protected $cast = array(
        'id'         => 'integer',
        'price'      => 'float',
        'is_awesome' => 'boolean'
    );

    ...

}
```

That's it. No service providers or facades required. Because it's a trait, however, you will need to be running PHP 5.4 or later.

Usage
-----

[](#usage)

Anytime you request an attribute listed in the `$cast` array, it will be converted from the (usually) string that your database returned into a the native PHP variable type you specified.

The keys of the `$cast` array are the attribute (i.e. column) names, and the values are the types you want to cast to. Anything supported by PHP's [settype()](http://php.net/manual/en/function.settype.php) function is valid ... although casting to arrays, objects, or null could be problematic.

If you set the `$castOnSet` property on your model to `true`, then setting an attribute that's in the `$cast` array will typecast that value before setting it. For example:

```
class MyModel {

    use EloquentTypecastTrait;

    protected $castOnSet = true;

    protected $cast = array(
        'price'      => 'float',
    );

}

$myModel = MyModel::find(1);

$price = Input::get('price');  // this will be a string
$myModel->price = $price;      // the string is cast to a float before setting;
```

In general, this setting isn't really necessary as Laravel and most databases will handle the string-to-column-type conversion for you on save. However, maybe there are cases where it's useful, so it's added for "feature completion".

Notes
-----

[](#notes)

Because of the way the trait works, you should make sure that your `$cast` array does not include:

- relations
- attributes for which you already have a custom mutator
- attributes using Eloquent's [date mutation](http://laravel.com/docs/eloquent#date-mutators)

`$model->toArray()` triggers the casting as well. `$model->getAttributes()`, however, does not. It returns the raw values from the query (not even the date mutation).

Bugs, Suggestions and Contributions
-----------------------------------

[](#bugs-suggestions-and-contributions)

Please use Github for bugs, comments, suggestions.

1. Fork the project.
2. Create your bugfix/feature branch and write your (well-commented) code.
3. Create unit tests for your code:
    - Run `composer install --dev` in the root directory to install required testing packages.
    - Add your test methods to `eloquent-typecast/tests/TypecastTest.php`.
    - Run `vendor/bin/phpunit` to the new (and all previous) tests and make sure everything passes.
4. Commit your changes (and your tests) and push to your branch.
5. Create a new pull request against the `develop` branch.

**Please note that you must create your pull request against the `develop` branch.**

Copyright and License
---------------------

[](#copyright-and-license)

Eloquent-Typecast was written by Colin Viebrock and released under the MIT License. See the [LICENSE.md](./LICENSE.md) file for details.

Copyright 2014 Colin Viebrock

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity39

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 71.4% 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 ~92 days

Total

3

Last Release

4144d ago

### Community

Maintainers

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

---

Top Contributors

[![cviebrock](https://avatars.githubusercontent.com/u/166810?v=4)](https://github.com/cviebrock "cviebrock (5 commits)")[![ntanis-dev](https://avatars.githubusercontent.com/u/59679141?v=4)](https://github.com/ntanis-dev "ntanis-dev (1 commits)")[![Torann](https://avatars.githubusercontent.com/u/1406755?v=4)](https://github.com/Torann "Torann (1 commits)")

---

Tags

jsonlaraveleloquentintegermutatorfloatbooleantypecastsettype

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/cviebrock-eloquent-typecast/health.svg)

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

###  Alternatives

[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-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)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[sebastiaanluca/laravel-boolean-dates

Automatically convert Eloquent model boolean attributes to dates (and back).

40111.7k1](/packages/sebastiaanluca-laravel-boolean-dates)

PHPackages © 2026

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