Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/spatie/laravel-data/llms.txt

Use this file to discover all available pages before exploring further.

The WithData trait enables support for the getData() method on Models, Requests, or any class that can be magically converted to a data object.

Using with Models

Add the trait and specify the data class:
class Song extends Model
{
    use WithData;
    
    protected $dataClass = SongData::class;
}
Quickly get the data object:
Song::firstOrFail($id)->getData(); // A SongData object

Using with Form Requests

For FormRequests, use a method instead of a property:
class SongRequest extends FormRequest
{
    use WithData;
    
    protected function dataClass(): string
    {
        return SongData::class;
    }
}
Use in a controller:
class SongController
{
    public function __invoke(SongRequest $request): SongData
    {
        $data = $request->getData();
    
        $song = Song::create($data->toArray());
        
        return $data;
    }
}

Benefits

Clean Controllers

Reduce boilerplate by calling getData() instead of SongData::from($model)

Type Safety

The data class is defined once and reused consistently

Discoverability

IDEs can autocomplete the data class from the model/request

Validation

Form requests automatically validate before creating the data object

Complete Example

// Model
class Song extends Model
{
    use WithData;
    
    protected $dataClass = SongData::class;
}

// Request
class StoreSongRequest extends FormRequest
{
    use WithData;
    
    protected function dataClass(): string
    {
        return SongData::class;
    }
    
    public function rules(): array
    {
        return [
            'title' => 'required|string',
            'artist' => 'required|string',
        ];
    }
}

// Controller
class SongController extends Controller
{
    public function store(StoreSongRequest $request)
    {
        $data = $request->getData();
        
        $song = Song::create($data->toArray());
        
        return $song->getData();
    }
    
    public function show(int $id)
    {
        return Song::findOrFail($id)->getData();
    }
}
The getData() method respects all the same creation rules as calling SongData::from() directly, including magic methods and validation.

Build docs developers (and LLMs) love