you can normalize or change request data structure with transformers.
lets normalize our data in
transformers
and letcontrollers
to be much more cleaner and smaller.
Via Composer
$ composer require shetabit/transform-request
we use transformers to transform request data.
you can run the below command in your console in order to create a new data transformer named TestTransformer
.
$ composer php artisan make:transformer TestTransformer
all transformers will be created in App\Http\Transformers
path.
in all transformers, the transform
method will transform your data into your ideal one.
for example we can write the below code in it:
namespace App\Http\Transformers;
use Shetabit\Transformer\Contracts\TransformerInterface;
class TestTransformer implements TransformerInterface
{
/**
* transform given data
*
* @param array $data
* @return array
*/
public function transform(array $data) : array {
/*
input data :
[
'n' => 'mahdi',
'f' => 'khanzadi'
]
transformed data:
[
'name' => 'mahdi',
'family' => 'khanzadi',
'username' => 'mahdikhanzadi'
]
*/
return [
'name' => $data['n'] ?? null,
'family' => $data['f'] ?? null,
'username' => ($data['n'] ?? null).($data['f'] ?? null)
];
}
}
we can use a transformer to transform requests like the below:
namespace App\Http\Controllers;
use App\Http\Transformers\TestTransformer;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function __invoke(Request $request) {
$data = $request->transform()->get(new TestTransformer());
print_r($data)
}
}
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING and CONDUCT for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.