Efficient Data Management with DTOs ( Data Transfer Objects) in Laravel

Rezaul H Reza 07 January 2023 Tutorial 3 minutes read

Data Transfer Objects

Data Transfer Objects (DTOs) are objects that are used to transfer data between layers of your application. They are often used to decouple the application's business logic from its data storage or presentation layers. So that we our business logics are in the DTOs and can be easily managed.

For example, let's say you have a Task Eloquent model that represents a task in your database. The Task model might have a title, description, and priority attribute, among others.

However, when you display a list of tasks to the user, you only want to show the title and priority of each task. Instead of creating a separate Eloquent model to represent this data, you could create a TaskListItemDTO that only has title and priority attributes.

Assume that we have the model `Task`.

It has columns:

title
description
priority


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    protected $fillable = ['title', 'description', 'priority'];
}


Let’s implement a TaskListItemDTO:



<?php
namespace App\DTOs;

class TaskListItemDTO
{
    public $title;
    public $priority;

    public function __construct(string $title, string $priority)
    {
        $this->title = $title;
        $this->priority = $priority;
    }
}


Now we will use it in our controller like this:


<?php

namespace App\Http\Controllers;

use App\DTOs\TaskListItemDTO;
use App\Task;

class TaskController extends Controller
{
    public function index()
    {
        $tasks = Task::all();
        $taskListItems = $tasks->map(function ($task) {
            return new TaskListItemDTO($task->title, $task->priority);
        });

        return view('tasks.index', ['taskListItems' => $taskListItems]);
    }
}


We can display the task list items as usually in ours blade file.



<ul>
    @foreach ($taskListItems as $task)
        <li>{{ $task->title }} ({{ $task->priority }})</li>
    @endforeach
</ul>

 


By using Data Transfer Objects, you can separate your business logic (represented by the Task model) from the presentation logic (represented by the TaskListItemDTO and the view used to display the tasks).



There you go guys! We can use DTOs to decouple our business logics and keep our application code cleaner then ever.



Related Posts

use-stripe-cli-with-laravel-herd-or-valet-or-nginx
Use Stripe CLI with Laravel Herd or Valet or nginx. 3 minutes read

Read more

Rezaul H Reza,17 February 2024
use-value-objects-in-laravel
Use Value Objects in Laravel 5 minutes read

Read more

Rezaul H Reza,07 January 2023

Write a comment

Comments (1)

Aslan Drees

1 year ago

Nice stuff! I should give it a go. Thanks for the suggestion

Leave a Reply

Rezaul H Reza

1 year ago

Thanks for your kind comment.