Blog Detail

19

Nov
How to Create Powerful and Rich Data objects for Laravel cover image

arrow_back How to Create Powerful and Rich Data objects for Laravel

Laravel-data is a package introduced by Spatie. This package enables the creation of rich data objects which can be used in various ways. Using this package you only need to describe your data once:

  • instead of a form request, you can use a data object
  • instead of an API transformer, you can use a data object
  • instead of manually writing a typescript definition, you can use… ? a data object

A laravel-data specific object is just a regular PHP object that extends from Data:

use Spatie\LaravelData\Data;

class SongData extends Data
{
    public function __construct(
        public string $title,
        public string $artist,
    ) {
    }
}

By extending from Data you enable a lot of new functionality like

  • Automatically transforming data objects into resources (like the Laravel API resources)
  • Transform only the requested parts of data objects with lazy properties
  • Automatically creating data objects from request data and validating them
  • Automatically resolve validation rules for properties within a data object
  • Make it possible to construct a data object from any type you want
  • Add support for automatically validating data objects when creating them
  • Generate TypeScript definitions from your data objects you can use on the frontend
  • Save data objects as properties of an Eloquent model
  • And a lot more …

Installation & setup

You can install the package via composer:

composer require spatie/laravel-data

Optionally, You can publish the config file with:

php artisan vendor:publish --provider="Spatie\LaravelData\LaravelDataServiceProvider"

Quickstart

In this quickstart, I’ll guide you through the most important functionalities of the package and how to use them.

First, you’ve to install the package.

We’re going to create a blog with different posts so let’s get started with the PostData object. A post has a title, some content, a status, and a date when it was published:

class PostData extends Data
{
    public function __construct(
        public string $title,
        public string $content,
        public PostStatus $status,
        public ?CarbonImmutable $published_at
    ) {
    }
}

The only requirement for using the package is extending your data objects from the base Data object. We add the requirements for a post as public properties.

The PostStatus is an enum using the spatie/enum package:

/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class PostStatus extends Enum
{

}

We store this PostData object as app/Data/PostData.php, so we have all our data objects bundled in one directory, but you’re free to store them wherever you want within your application.

We can now create this a PostData object just like any plain PHP object:

$post = new PostData(
    'Hello laravel-data',
    'This is an introduction post for the new package',
    PostStatus::published(),
    CarbonImmutable::now()
);

The package also allows you to create these data objects from any type, for example, an array:

$post = PostData::from([
    'title' => 'Hello laravel-data',
    'content' => 'This is an introduction post for the new package',
    'status' => PostStatus::published(),
    'published_at' => CarbonImmutable::now(),
]);

Advanced Usage

The Laravel data package also includes flexible and advanced features:

  • Eloquent casting
  • Transforming to TypeScript
  • Taking simple values and casting them into complex types
  • Taking complex values and transforming them into simple types
  • Creating a rule inferrer
  • Data Object validation attributes using PHP 8.0 attributes

Here is a short introduction of the functionalities of this package, For more details, You can visit its detailed documentation and source code on Github.

Published at : 19-11-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project