jgrossi / laravel-mutable
Change model attributes values easily
0.1.1
2017-07-20 17:40 UTC
Requires
- illuminate/database: ~5.0
Requires (Dev)
- phpunit/phpunit: ^6.2
This package is auto-updated.
Last update: 2024-11-21 20:49:58 UTC
README
Change Laravel models
toArray()
values using a simple and clean way
Installation
composer require jgrossi/laravel-mutable
Usage
First add Mutable
trait to the model you want to change values:
use Jgrossi\Mutable\Mutable; class User extends Eloquent { use Mutable; }
Then create a UserMutator
class in any place in your app (or give it other name if you prefer). Then set the $mutator
property in your model:
use App\Models\Mutators\UserMutator; use Jgrossi\Mutable\Mutable; class User extends Eloquent { use Mutable; protected $mutator = UserMutator::class; }
In your mutator class you might have one method for each attribute you want to change:
namespace App\Models\Mutators; use Carbon\Carbon; use Jgrossi\Mutable\Mutator; class UserMutator extends Mutator { public function firstName($value) { return ucfirst($value); } public function createdAt(Carbon $date) { return $date->format('Y-m-d'); } }
Then when using $user->toArray()
you'll have the first_name
attributes changed.
class FooController extends Controller { public function show($id) { $user = User::findOrFail($id); return $user; // returns the changed User as array } }
Licence
MIT License © Junior Grossi