DEV Community

Gurpreet Kait
Gurpreet Kait

Posted on • Originally published at larachamp.com on

Why Use Laravel Data?

I’ve been using Laravel Data for the last 1 month and I found that it’s a time saver if you don’t want to debug your arrays when passing into functions/methods as parameters.

In this blog post, we’ll explore its key features, and why you should consider using it in your next Laravel project.

What is Laravel Data?

Spatie developed this package to simplify data transfer and transformation within Laravel applications. It allows you to easily manage data coming into and going out of your application, ensuring that it is properly formatted, validated, and transformed as needed.

Understand By Example

As always let’s take an example to understand how Laravel Data works. So, let’s say we are going to store users from a request Route::post('user',[UserController::class,'store']) now, let’s see how Laravel Data can handle this request.

We will create a Data(DTO – Data Transfer Object) File (a simple PHP file which extends to the base class).

App -> Data -> UserData.php
Enter fullscreen mode Exit fullscreen mode

Now let’s see how UserData will work.

<?php

namespace App\Data;

use Spatie\LaravelData\Data;
use Spatie\LaravelData\Optional;

class UserData extends Data
{
    public function __construct(
        public string $username,
        public int $mobile,
        public int|Optional $age,
        public bool|Optional $is_student,
        public bool|Optional $is_teacher,
    )
    {

    }
}

Enter fullscreen mode Exit fullscreen mode

Now we can directly use it in our controller instead Request.

<?php

namespace App\Http\Controllers;

use App\Data\UserData;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function store(UserData $data)
    {
        User::create($data->toArray());
    }
}

Enter fullscreen mode Exit fullscreen mode

So, now you should be worried about how you gonna pass extra rules to it? I mean, if you want to validate the max, min, email, etc. Yes, we easily can do that we just need to modify our UserData Class.

 public function __construct(
        #[Max(20)] // you can add these attributes
        public string $username,
        #[Digits(10)] // you can add these attributes
        public int $mobile,
        public int|Optional $age,
        public bool|Optional $is_student, // you can use Optional to avoid validation
        public bool|Optional $is_teacher, // you can use Optional to avoid validation
    )
Enter fullscreen mode Exit fullscreen mode

If you think that you want to add multiple attributes then you can explore Required() and ofcourse you’ll not be satisfied by these examples. I’ll suggest to you to explore Laravel Data Validation Attributes.

Installation

You can easily install the Laravel Data Package by using the mentioned command.

composer require laravel-data/laravel-data
Enter fullscreen mode Exit fullscreen mode

Benefits Of Using LaravelData

Cleaner Code : DTO helps us to keep code organized by using Data Transfer Objects (DTOs) to manage data, making it easier to read and maintain.

Easy Validation : You can simplify data validation by defining validation rules directly in your DTOs, ensuring that data is correct before processing it.

Automatic Data Transformation : DTO automatically transforms data between different formats, saving the time and reducing errors when working with APIs.

Type Safety : By defining data types in DTOs, it helps catch errors early, ensuring that your data is always in the expected format.

Simplified Serialization : It makes serializing and deserializing data easy, so you can quickly convert data to and from formats like JSON, without writing extra code.

Read Also : Create Custom Laravel Helpers

Conclusion

So, in short, this package (DTO) simplifies and enhances data management in Laravel applications.

The post Why Use Laravel Data? appeared first on Larachamp.

Top comments (0)