Reducing code duplication

Published on by

Reducing code duplication image

Code duplication is the most painful thing for a lot of developers, you think you have solved the problem, but there are several instances of the same issue.

In many of the codebases I have seen as a Laravel developer, the console commands always seem to be the forgotten area or the part where people need to pay more attention to the quality.

In this tutorial, I will walk through how you can approach writing code with a focus on reducing code duplication. To begin with, let's pose a hypothetical. We have a Laravel application that is an e-commerce store, and once a day, we want to generate a report on all the sales and the status of shipments. Our current approach is to log in to the administration panel and click a button to generate the report.

This may be unrealistic, as the first instance here would be to automate it. But stick with me just a little while as we venture through this idea to improve it.

Our first step will be to create an artisan command or set of artisan commands that will generate the reports. As we start looking at reporting, it makes sense to have commands explicitly named for what we want to achieve. So let us begin with the sales figures.

final class SalesFigures extends Command
{
public $signature = 'reports:sales';
 
public $description = 'Run a daily report on sales.';
 
public function handle(): int
{
$date = now()->subDay();
 
$sales = Order::query()
->where('status', Status::COMPLETE)
->whereBetween(
'completed_at',
$date->startOfDay(),
$date->endOfDay(),
)->latest()->get();
 
// send information through to the report builder
}
}

We have a simple command here that we will be able to run and get sales figures for yesterday that are marked as complete. The query itself is simple enough. It checks the status and date was yesterday, then orders them, so the latest is first - to allow us to build a chronological report.

How can we improve this, though? Are there other aspects of the application where we need to get these orders in a similar order? Let's start the refactoring process.

Firstly, this specific query is something that we need to run in a few different areas. So we can move this to its own class for us to run.

final class ResultsForPeriod implements ResultsForPeriodContract
{
public function handle(
Builder $query,
CarbonInterface $start,
CarbonInterface $end,
): Builder {
return $builder->whereBetween(
'completed_at',
$start,
$end,
);
}
}

This will allow us to get the results for a certain timespan across any models - which is more beneficial for the project.

final class SalesFigures extends Command
{
public $signature = 'reports:sales';
 
public $description = 'Run a daily report on sales.';
 
public function handle(ResultsForPeriodContract $query): int
{
$date = now()->subDay();
 
$sales = $query->handle(
query: Order::query()
->where('status', Status::COMPLETE),
start: $date->startOfDay(),
end: $date->endOfDay()
)->latest()->get();
 
// send information through to the report builder
}
}

We have implemented the query we built for filtering based on a timespan. Where else can we take this to make it cleaner and more efficient? Could we create a specific service to handle this reporting aspect? Is this service helpful in other areas too?

Our e-commerce dashboard will likely have some information from these reports, so some code reuse is already in place. Let's move this to a service.

final class ReportService implements ReportServiceContract
{
public function __construct(
private readonly ResultsForPeriodContract $periodFilter,
) {}
 
public function dailySales(CarbonInterface $start, CarbonInterface $end): Collection
{
return $this->periodFilter->handle(
query: Order::query()->where('status', Status::COMPLETE),
)->latest()->get();
}
}

We can now move this back into the artisan command.

final class SalesFigures extends Command
{
public $signature = 'reports:sales';
 
public $description = 'Run a daily report on sales.';
 
public function handle(ReportServiceContract $service): int
{
$date = now()->subDay();
 
$sales = $service->dailySales(
query: Order::query(),
start: $date->startOfDay(),
end: $date->endOfDay()
);
 
// send information through to the report builder
}
}

As you can see, we have a new clean command that nicely utilizes shared code with other areas of our application.

Steve McDougall photo

Technical writer at Laravel News, Developer Advocate at Treblle. API specialist, veteran PHP/Laravel engineer. YouTube livestreamer.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article