Package Data | |
---|---|
Maintainer Username: | jgrossi |
Maintainer Contact: | juniorgro@gmail.com (Junior Grossi) |
Package Create Date: | 2017-07-20 |
Package Last Update: | 2017-07-20 |
Home Page: | |
Language: | PHP |
License: | MIT |
Last Refreshed: | 2024-11-24 03:01:16 |
Package Statistics | |
---|---|
Total Downloads: | 18 |
Monthly Downloads: | 0 |
Daily Downloads: | 0 |
Total Stars: | 1 |
Total Watchers: | 3 |
Total Forks: | 0 |
Total Open Issues: | 0 |
Change Laravel models
toArray()
values using a simple and clean way
composer require jgrossi/laravel-mutable
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
}
}
MIT License © Junior Grossi