Giter VIP home page Giter VIP logo

laravel-mutate's Introduction

Eloquent Mutators

License Latest Stable Version StyleCI Tests

This package allows you to map your model attributes to database columns when the type in the PHP model does not match the type in the database column.

This could be using $model->ip_address as a string in your eloquent model but storing it as a BINARY(16) in the database for efficiency. Or having a string always encrypted in the DB but readable in clear form within your models.

Installing

$ composer require weebly/laravel-mutate

To use this package, you'll need to add the ServiceProvider to the providers array in config/app.php if you are not using automatic package discovery:

Weebly\Mutate\LaravelMutatorServiceProvider::class

You'll also need to publish the config to config/mutators.php with:

$ php artisan vendor:publish --provider='Weebly\Mutate\LaravelMutatorServiceProvider'

Usage

When creating an Eloquent model, you'll need to extend Weebly\Mutate\Database\Model and add $mutate property it:

<?php

namespace App\Models;

use Weebly\Mutate\Database\Model;

class User extends Model
{
    /**
     * {@inheritdoc}
     */
    protected $table = 'users';

    /**
     * {@inheritdoc}
     */
    protected $mutate = [
        'id' => 'uuid_v1_binary'
    ];
}

This will automatically serialize/unserialize the id attribute on the User model when getting/setting the attribute from the database. This allows you to no longer need to set accessors/mutator methods on the model directly.

Note: Unlike the built in Laravel accessors/mutators, this package will serialize the attribute values when they are passed to an Eloquent query builder.

Included Mutators

  • uuid_v1_binary Will take a uuid version 1, re-order its bytes so that if uuidA was generated before uuidB, then storedUuidA < storedUuidB, and store it in the database as 16 bytes of data. For more information on the re-ordering of bytes, see: https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/.
  • ip_binary Will take a string representation of an IPv4 or IPv6 and store it as 16 bytes in the database.
  • encrypt_string Will take a non encrypted string and encrypt it when going to the database.
  • hex_binary Will take any hexadecimal string attribute and store it as binary data.
  • unix_timestamp Will take a Carbon date but store it as an integer unix timestamp.

Creating Custom Mutators

To define a custom mutator, you'll need to create a class that implements Weebly\Mutate\Mutators\MutatorContract, and add it to the enabled array in config/mutators.php.

Note: All attributes are cached on a model instance automatically, so you should not need to add any caching logic at the mutator level.

When building and registering a Mutator, it is important to know that they are resolved automatically from the Laravel IOC container, which means you may create service providers for them if they require custom constructor arguments.

<?php

namespace App\Mutators;

use Weebly\Mutate\Mutators\MutatorContract;

class ExampleEncryptMutator implements MutatorContract
{
    /**
     * {@inheritdoc}
     */
    public function serializeAttribute($value)
    {
        return encrypt($value);
    }

    /**
     * {@inheritdoc}
     */
    public function unserializeAttribute($value)
    {
        return decrypt($value);
    }
}

Testing

Running tests:

$ ./vendor/bin/phpunit

License

This package is open-sourced software licensed under the 2-Clause BSD license.

laravel-mutate's People

Contributors

birddgp avatar bmwong avatar bobo333 avatar bryanashley avatar dustindoiron avatar elliotfehr avatar khepin avatar skozak-sq avatar stylecibot avatar suadhuskic avatar szainmehdi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-mutate's Issues

Model::find() with array of ids return empty collection

Steps to reproduce:
Suppose someuuid1 is just generic uuid_v1.

php artisan tinker
Psy Shell v0.8.11 (PHP 7.1.9-1+0~20170902060745.8+stretch~1.gbpebe5d6 — cli) by Justin Hileman

>>> Site::find(['someuuid1']);
[!] Aliasing 'Site' to 'App\Models\Eloquent\Site' for this Tinker session.
=> Illuminate\Database\Eloquent\Collection {#813
     all: [],
   }

>>> Site::find('someuuid1');
=> App\Models\Eloquent\Site {#826
     id: b"ùUêØ:\x05G█ø*═ùª\vo¶",
   }

Quick investigation on this showed that inserting array of IDs to find() doesn't go through any mutation at all.
Eloquent builder extending on whereIn is not being called.
WhereIn doesn't seem to exist in default eloquent builder as well.
I thought it was being inherited since I saw @inhertitdoc present on docblock?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.