Laravel Mutable
Change Laravel models toArray() values using a simple and clean way, (*1)
Installation
composer require jgrossi/laravel-mutable
Usage
First add Mutable trait to the model you want to change values:, (*2)
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:, (*3)
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:, (*4)
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., (*5)
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, (*6)