Package Data | |
---|---|
Maintainer Username: | slruslan |
Maintainer Contact: | me@slinkov.xyz (Ruslan Slinkov) |
Package Create Date: | 2017-04-17 |
Package Last Update: | 2017-05-20 |
Language: | PHP |
License: | GPL |
Last Refreshed: | 2025-02-09 15:05:21 |
Package Statistics | |
---|---|
Total Downloads: | 159 |
Monthly Downloads: | 0 |
Daily Downloads: | 0 |
Total Stars: | 5 |
Total Watchers: | 3 |
Total Forks: | 1 |
Total Open Issues: | 0 |
Laravel Eloquent provides an Attribute Casting function, that allows you to automatically convert attributes to common data types.
By default, supported cast types are: integer, real, float, double, string, boolean, object, array, collection, date, datetime, and timestamp.
As you can see, custom class types are not supported. This trait adds this support, so you automatically serialize and deserialize your custom classes.
Using Composer:
$ composer require slruslan/laravel-eloquent-custom-casts --dev
Create a field of TEXT type where your data will be stored.
To enable trait, add use Slruslan\CustomCasts\CustomCasts;
line to your Eloquent Model class.
For example:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Slruslan\CustomCasts\CustomCasts;
class Post extends Model
{
use CustomCasts;
protected $casts = [
'geo_location' => \App\Services\CustomLocation::class,
'another_custom_field' => \App\Services\AnotherCustomField::class
];
$post = Post::find(1);
// For example, imagine we have an \App\Services\CustomLocation class,
// that implements any custom logics and for some reasons
// we have to store it in DB as it is.
// Let's instantinate it.
$location = new \App\Services\CustomLocation(55.9937441, 92.7521816);
// And call some methods, imagine we have them there.
$location->updatePosition();
$location->callAPI();
// After that, we want to save it in our post model.
// We can just assign the value and call default save() method.
$post->geo_location = $location;
$post->save();
// It's saved. Let's get a post again
// and check the field class.
$post = Post::find(1);
var_dump($post instanceof \App\Services\CustomLocation);
// Outputs:
// bool(true)
GNU General Public License v3.0 (GPL). Refer to the LICENSE file to get more info.
You can ask me any questions by:
Email: me@slinkov.xyz
VK: vk.com/slruslan