19
NovLaravel-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:
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
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"
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(),
]);
The Laravel data package also includes flexible and advanced features:
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
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 project