Laravel Custom Casts Package

Laravel Custom Casts Package

Make your own cast type for Laravel model attributes

Originally published at https://github.com

Laravel custom casts works similarly to Laravel attribute casting, but with our customly defined logic (in separated class). This means that we can use the same casting logic across our models - we might write image upload logic and use it everywhere. Beside casting to our custom types this package gives us ability to listen and react to underlying model events.

Let's check out some Laravel common cast types and possible example of their usage:

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model { protected $casts = [ 'is_admin' => 'boolean', 'login_count' => 'integer' 'height' => 'decimal:2' ]; }

Beside bolean, integer and decimal from the example above, out of the box Laravel supports real, float, double, string, object, array, collection, date, datetime, and timestamp casts.

Sometimes it is convenient to handle more complex types with custom logic and ability to listen and react to model events. This is where this package come in handy.

Handling events directly from custom casts could be very useful if we're, for e.g. storing image with custom casts and we need to delete it when the model gets deleted. Checkout the old documentation for this example.


vkovic packages

Please checkout my other packages - they are all free, well written and some of them are useful. If you find something interesting you might give me a hand for further package development, suggest an idea or some kind of improvement, star the repo if you like it or simply check out the code - there's a lot of useful stuff under the hood.

Compatibility

The package is compatible with Laravel and Lumen versions 5.5, 5.6, 5.7 and 5.8.

Installation

Install the package via composer:

composer require vkovic/laravel-custom-casts

Usage


Utilizing a custom casts class

To enable custom casts in our models, we need to use HasCustomCasts trait and we need to define which filed will be casted - per Laravel standards.

// File: app/User.php

namespace App;

use App\CustomCasts\NameCast; use Illuminate\Database\Eloquent\Model; use Vkovic\LaravelCustomCasts\HasCustomCasts;

class User extends Model { use HasCustomCasts;

protected $casts = [
    'is_admin' => boolean // <-- Laravel default cast type
    'name' => NameCast::class // <-- Our custom cast class (follow section below)
];

}


Defining custom cast class

This class will be responsible for our custom casting logic.

// File: app/CustomCasts/NameCast.php

namespace App\CustomCasts;

use Vkovic\LaravelCustomCasts\CustomCastBase;

class NameCast extends CustomCastBase { public function setAttribute($value) { return ucwords($value); }

public function castAttribute($value)
{
    return $this->getTitle() . ' ' . $value;
}

protected function getTitle()
{
    return ['Mr.', 'Mrs.', 'Ms.', 'Miss'][rand(0, 3)];
}

}

Required setAttribute method receives $value that we're setting on our model field and should return raw value that we want to store in our database.

Optional getAttribute method receives raw $value from database and should return mutated value. If we omit this method, raw value from database will be returned.

For the sake of this example we'll implement one more method which will attach random title to our users when name is returned from database.

Let's test it

Let's create a user and see what will happen.

$user = new App\User;
$user->name = 'john doe';

$user->save();

This will create our new user and his name will be stored in the database, first letters uppercased.

When we retrieve our user and try to get his name, title will be prepended to it, just like we defined it in our custom NameCast class.

dd($user->name); // 'Mr. John Doe'

Handling model events

Let's say that we want to notify our administrator when user name changes.

// File: app/CustomCasts/NameCast.php

public function updated() { $attribute = $this->attribute;

if($this->model->isDirty($attribute)) {
    // Notify admin about name change
}

}

Beside updated method, we can as well create other methods for standard model events: retrieved, creating, created, updating, saving, saved, deleting, deleted, restoring and restored.

Other functionality

As you can assume from code above, we can easily access casted attribute name as well as instance of underlying model.

// File: app/CustomCasts/NameCast.php

// Get model attribute name being casted dd($this->attribute); // 'name'

// Access our User model dd(get_class($this->model)); // 'App/User'

Beside this we can retrieve all casted attributes and their corresponding classes directly from our model.

// File: app/User.php

dd($this->getCustomCasts()); // ['name' => 'App/CustomCasts/NameCast']


More examples

You can find more examples on the old documentation.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Further reading

PHP with Laravel for beginners - Become a Master in Laravel

Projects in Laravel: Learn Laravel Building 10 Projects

Laravel for RESTful: Build Your RESTful API with Laravel

Fullstack Web Development With Laravel and Vue.js

Laravel 5.8 Tutorial for Beginners

Laravel 5.8 Ajax CRUD tutorial using Datatable JS

Laravel 5.8 Tutorial from Scratch for Beginners

Build RESTful API In Laravel 5.8 Example

Login with Google in Laravel 5.8 App using Socialite Package

Laravel PHP Framework Tutorial - Full Course for Beginners (2019)

laravel php web-development

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

PHP Web Application Development Company

As a top **PHP Web Application Development Company in USA**[https://www.dataeximit.com/php-development-services/](https://www.dataeximit.com/php-development-services/ "https://www.dataeximit.com/php-development-services/"), we at Data EximIT have...

PHP Website Development

Skenix Infotech is a leading PHP Web Development Company that helps companies get results with industry best practices. Get affordable PHP Development Services.

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers? **[Hire Dedicated PHP Developer](https://hourlydeveloper.io/hire-dedicated-php-developer/ "Hire Dedicated PHP Developer")**, who can convert your idea to reality, within the stipulated...

Advantages of Hiring PHP Developer for your Website Project

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is...

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...