In components such as Data and Form, you may want to pass PHP objects to the frontend. The most common example is an Eloquent Model. Though you may hide sensitive attributes from being passed to the frontend, and though the Form Components have built-in support to guard Model attributes, you may also choose to use a Transformer.
Splade makes it very easy to define a Transformer once, and use it throughout the application in the Data, Defer, Form, and Bridge Components. It supports Eloquent API Resources, Fractal Transformers, and a simple closure.
Configuring a Transformer is as easy as calling the transformUsing
method on the Splade
facade, for example, in the AppServiceProvider
class:
Splade::transformUsing(User::class, UserResource::class);
Instead of calling the transformUsing
methods multiple times, you may also pass an array:
Splade::transformUsing([
Team::class => TeamResource::class,
User::class => UserResource::class,
]);
When no Transformer has been configured, Splade won't transform the given data and passes it untouched. If you want to enforce using Transformers, and protect against missing Transformers, you may call the requireTransformer
method on the Splade
facade:
Splade::requireTransformer();
To use Fractal Transformers, you need to install the spatie/fractalistic
package.
Splade::transformUsing(User::class, UserTransformer::class);
For simple transformations, you may pass a closure:
Splade::transformUsing(User::class, function ($user) {
return [
'name' => $user->name,
'email' => $user->email,
];
});