PHPackages                             movor/laravel-custom-casts - 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. movor/laravel-custom-casts

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

movor/laravel-custom-casts
==========================

Make your own custom cast type for Laravel model attributes

v0.2.1(7y ago)5172MITPHP

Since Aug 9Pushed 7y ago1 watchersCompare

[ Source](https://github.com/movor/laravel-custom-casts)[ Packagist](https://packagist.org/packages/movor/laravel-custom-casts)[ RSS](/packages/movor-laravel-custom-casts/feed)WikiDiscussions master Synced 2mo ago

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

Laravel Custom Casts
====================

[](#laravel-custom-casts)

[![Build](https://camo.githubusercontent.com/9aed99c978e085665a1b67d10fd93a1c01d8e051af2d3ff66c5f5ed1f38c6266/68747470733a2f2f6170692e7472617669732d63692e6f72672f6d6f766f722f6c61726176656c2d637573746f6d2d63617374732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/movor/laravel-custom-casts)[![Downloads](https://camo.githubusercontent.com/513813cf891bf9bc02d20a0e9242a8b19523129deee52a6dbe7ebe176cb978cb/68747470733a2f2f706f7365722e707567782e6f72672f6d6f766f722f6c61726176656c2d637573746f6d2d63617374732f646f776e6c6f616473)](https://packagist.org/packages/movor/laravel-custom-casts)[![Stable](https://camo.githubusercontent.com/d8f94aaa90635bf1d1a637fdc51d98167b4babbd14e3f701a24a187e8c1eca91/68747470733a2f2f706f7365722e707567782e6f72672f6d6f766f722f6c61726176656c2d637573746f6d2d63617374732f762f737461626c65)](https://packagist.org/packages/movor/laravel-custom-casts)[![License](https://camo.githubusercontent.com/8503a3ffb41a0916758accda6eb2849e3ce117fcd195c83f6caccf602d57d2bb/68747470733a2f2f706f7365722e707567782e6f72672f6d6f766f722f6c61726176656c2d637573746f6d2d63617374732f6c6963656e7365)](https://packagist.org/packages/movor/laravel-custom-casts)

### Make your own custom cast type for Laravel model attributes

[](#make-your-own-custom-cast-type-for-laravel-model-attributes)

By default, from version 5 Laravel supports attribute casting. If we define `$cast` property on our model, Laravel will help us convert defined attributes to common data types. Currently supported cast types (Laravel 5.6) are: `integer`, `real`, `float`, `double`, `string`, `boolean`, `object`, `array`, `collection`, `date`, `datetime` and `timestamp`.

If those default cast types are not enough and you want to make your own, you'r on the right track.

---

❗❗❗ **MOVING GIT REPOSITORY**❗❗❗

This package **repo and maintenance will continue on**:

[**vkovic/laravel-custom-casts**](https://github.com/vkovic/laravel-custom-casts).

🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚

---

Compatibility
-------------

[](#compatibility)

The package is compatible with Laravel versions `>= 5.1`

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

[](#installation)

Install the package via composer:

```
composer require movor/laravel-custom-casts
```

Example: Casting User Image
---------------------------

[](#example-casting-user-image)

When saving an image, there is two things that needs to be done:

1. Save image name (sometimes with path) into corresponding database field
2. Save image physically on the disk

As a guidance for this example we'll use default Laravel user model found in `app/User.php`.

Beside basic, predefined fields: `name`, `email` and `password`, we also want to allow user to upload his avatar. Assume that we already have `users` table with `image` field (you should create seeder for this).

To utilize custom casts, we'll need to add trait to user model, and via `$casts` property link it to the cast class.

```
// File: app/User.php

namespace App;

use App\CustomCasts\ImageCast;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Movor\LaravelCustomCasts\HasCustomCasts;

class User extends Authenticatable
{
    use Notifiable, HasCustomCasts;

    protected $fillable = [
        'name', 'email', 'password', 'image'
    ];

    protected $hidden = [
        'password', 'remember_token'
    ];

    protected $casts = [
        'image' => ImageCast::class
    ];
}

// ...
```

Next step is to create class that'll handle casting. It must implement `setAttribute` method which will take care of saving the image (from UploadedFile object, via form upload in this case) and generating image name with path - to be preserved in database.

```
// File: app/CustomCasts/ImageCast.php

namespace App\CustomCasts;

use Movor\LaravelCustomCasts\CustomCastBase;
use Illuminate\Http\UploadedFile;

class ImageCast extends CustomCastBase
{
    public function setAttribute($file)
    {
        // Define storage folder
        // (relative to "storage/app" folder in Laravel project)
        // Don't forget to create it !!!
        $storageDir = 'images';

        // Generate random image name
        $filename = str_random() . '.' . $file->extension();

        // Save image to predefined folder
        $file->storeAs($storageDir, $filename);

        // This will be stored in db field: "image"
        return $storageDir . '/' . $filename;
    }
}
```

Let's jump to user creation example. This will trigger our custom cast logic.

Assume that we have user controller which will handle user creation. You should create this on your own.

> Code below is just a simple example and should be used as guidance only.

```
// File: app/Http/Controllers/UserController.php

// ...

protected function create(Request $request)
{
    User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password),
        // Past the whole Illuminate\Http\UploadedFile object,
        // we'll handle it in our ImageCast class
        'image' => $request->file('image')
    ]);
}

// ...
```

Visit corresponding route input basic details and attach the image. After that, we'll have our user created and image stored.

But we should also handle deleting image when user is deleted. This can be accomplished by utilizing underlying eloquent events handling. Each time eloquent event is fired, logic will look up for public method with the same name in our custom cast class.

Possible method names are: `retrieved`, `creating`, `created`, `updating`, `updated`, `saving`, `saved`, `deleting`, `deleted`, `restoring` and `restored`.

```
// File: app/CustomCasts/ImageCast.php

// Add at the top
use Storage;

// ...

// This method will be triggered after model has been deleted
public function deleted()
{
    // We can access underlying model with $this->model
    // and attribute name that is being casted with $this->attribute

    // Retrieve image path and delete it from the disk
    $imagePath = $this->model->image;
    Storage::delete($imagePath);
}

// ...
```

This should cover basics usage of custom casts.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

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

Total

4

Last Release

2720d ago

### Community

Maintainers

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

---

Top Contributors

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

---

Tags

accessorattributecastcastingcustomlaravelmutatorlaravelmodelcastdatatypecasts

### Embed Badge

![Health badge](/badges/movor-laravel-custom-casts/health.svg)

```
[![Health](https://phpackages.com/badges/movor-laravel-custom-casts/health.svg)](https://phpackages.com/packages/movor-laravel-custom-casts)
```

###  Alternatives

[vkovic/laravel-custom-casts

Make your own custom cast type for Laravel model attributes

218362.7k3](/packages/vkovic-laravel-custom-casts)[wendelladriel/laravel-lift

Take your Eloquent Models to the next level

70046.8k](/packages/wendelladriel-laravel-lift)[esensi/model

The base model traits of Esensi

20266.5k1](/packages/esensi-model)[waad/laravel-model-metadata

A robust Laravel package for handling metadata with JSON casting, custom relation names, and advanced querying capabilities.

823.1k](/packages/waad-laravel-model-metadata)[renoki-co/laravel-useful-casts

Laravel Useful Casts is a simple package for Laravel 7.0+ that comes with already-tested and already-written, useful casts for Eloquent models.

103.6k1](/packages/renoki-co-laravel-useful-casts)

PHPackages © 2026

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