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)

Hire PHP Developer and Web Developer for your Online Business

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...

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 development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]

Laravel Framework Development Services | Laravel Web Development

CMARIX is leading Laravel Web application Development Service Provider with the track record of implementing diverse high-performance Laravel web applications with skilled Laravel developer team for clients across the globe<a href="https://www.cmarix.com/laravel-framework-development-services.html?utm_source=SB" target="_blank">.Continue</a>

CMARIX is leading Laravel Web application Development Service Provider with the track record of implementing diverse high-performance Laravel web applications with skilled Laravel developer team for clients across the globe.Continue

Which is the best PHP Web Development Company in India?

Which is the best PHP Web Development Company in India?

Many experienced players prefer to give it a go ahead with PHP for their web development needs because of the simplicity that PHP provides. PHP is loaded with features that many other languages lack and those pre-defined features can bring new functionalities and finishing touch to your existing or new website that you are looking forward to create. Wouldn’t it be great to get the best PHP Web Development Company for your project; we have a reputation as few of the leading firms in IT industry when it comes to PHP development.

Perks you should keep an eye out for before considering to outsource project to any web development company:

1. Company’s Reputation- It is very important to know about the previous projects that the company has delivered and the success rate of those products. You can visit company’s website for client testimonials or can google reviews given to them by genuine clients. We follow transparency, you can contact our previous clients and let them tell you how their experience was while working with us.

2. Technical Skill set and Expertise- You should select a company that has multiple resource pool of expert and technically sound developers. Our developers are experienced with different PHP frameworks and are exceptionally good with writing bug free codes. You can also hire PHP developer in India from us, as our developers have on hand experience in PHP development (core and frameworks)

3. The Budget- Costing has always played as one of the most important roles in every business deal. We provide competitive pricing with no hidden cost guaranteed. With us you can expect your project to be in best quality with no compromise to be made even with the best price in the market.

Why Data EximIT is the best PHP web development company in India?

Here are some of the features that might love about Data EximIT:

 Reputation of Data EximIT is wonderful among the previous clients.

 We have around 87% of retention ratio of clients.

 We were time committed, means every milestone was achieved before or on time.

 Data EximIT follows Agile development so it was the best possible methodology.

 We have huge team with different expertise over multiple PHP frameworks, so you are provided with ample to options to choose from.

 We are very active in communication part. Method or time of communication was never an issue at Data EximIT.

 We have some of the best designers to ensure that your project not only functions but also looks and feels fabulous.

 We provided customers with best costing without compromising on the quality at all.

 We also provide dedicated PHP developer or team of PHP developers on hire for your project.

Data EximIT is where customers feel confident to come up with idea and leave with fully functioning & best in quality projects. You can also avail our developers at your requested site location if you decide to hire PHP developers in India from us.

Feel free to contact our experts and let success reach you by working with the best PHP web development company.