Skip to content

Transform Eloquent Model Data

Introduction

The built-in Query Builder ensures that only the necessary data from an Eloquent Model is passed to the frontend. This is based on the columns of your Inertia Table. For example, if you have a users database table with columns id, name, email, and password, and your Inertia Table only has columns for name and email, then only the name and email attributes will be passed to the frontend.

While you can transform the data per column using the mapAs argument and method, there are still cases where you want full control over the data transformation.

Transforming Data

You may transform the data of an Eloquent Model by using the transformModel method on your Table class. This method accepts the Eloquent Model instance and the transformed data as arguments. You must return an array of the transformed data.

php
use Illuminate\Support\Str;

class Users extends Table
{
    public function transformModel(Model $model, array $data): array
    {
        return [
            'key' => $model->id,
            'name' => $model->generateFullName(),
            'email' => Str::mask($model->email),
        ];
    }
}

In the example above, the $data argument is unused, and a whole new array is returned. But sometimes, you just want to add or change a few little things. In this case, you can use the $data argument.

php
class Users extends Table
{
    public function transformModel(Model $model, array $data): array
    {
        return [
            ...$data,
            'avatar_url' => $user->avatar_path ? Storage::url($user->avatar_path) : null,
        ];
    }
}