jgrossi/laravel-mutable
Laravel Mutable
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
Related Packages
Powerful PHP database abstraction layer (DBAL) with many features for database s...
Laravel Serializable Closure provides an easy and secure way to serialize closur...
Cli error handling for console/command-line PHP applications.
Version History
| Version | Released | Laravel | License |
|---|---|---|---|
| 0.1.1 | ~5.0 | MIT | |
| 0.1.0 | ~5.0 | MIT |