Courses

Larastan: Catch Bugs with Static Analysis

Once we switch to higher levels of Larastan - we'll start to see more errors that are stricter and could be a great help. Let's set up the example:

app/Services/ClientReportsService.php

<?php
 
namespace App\Services;
 
use App\Models\Transaction;
use Carbon\Carbon;
 
class ClientReportsService
{
public function getReport($request)
{
$query = Transaction::with('project')
->with('transaction_type')
->with('income_source')
->with('currency')
->orderBy('transaction_date', 'desc');
 
if ($request->has('project')) {
$query->where('project_id', $request->input('project'));
}
 
$transactions = $query->get();
 
$entries = [];
foreach ($transactions as $row) {
$date = Carbon::createFromFormat(config('panel.date_format'), $row->transaction_date)->format('Y-m');
if (!isset($entries[$date])) {
$entries[$date] = [];
}
$currency = $row->currency->code;
if (!isset($entries[$date][$currency])) {
$entries[$date][$currency] = [
'income' => 0,
'expenses' => 0,
'fees' => 0,
'total' => 0,
];
}
$income = 0;
$expenses = 0;
$fees = 0;
if ($row->amount > 0) {
$income += $row->amount;
} else {
$expenses += $row->amount;
}
if (!is_null($row->income_source->fee_percent)) {
$fees = $row->amount * ($row->income_source->fee_percent / 100);
}
 
$total = $income + $expenses - $fees;
$entries[$date][$currency]['income'] += $income;
$entries[$date][$currency]['expenses'] += $expenses;
$entries[$date][$currency]['fees'] += $fees;
$entries[$date][$currency]['total'] += $total;
}
 
return $entries;
}
}

For this we'll expand our code example with our Relationship definitions to better see the whole picture:...

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 68 courses (1183 lessons, 43 h 18 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord