Certainly! Here’s how you can approach this in Laravel, using Eloquent relationships and query builder. I’ll break it down step by step:
1. Database Structure Assumptions
InventoryInStorehasbuying_priceandselling_pricecolumns.SoldInventoryhasdate_of_saleandstore_id.SoldInventoryItemshasquantityand links toinventory_in_store_id.
If your table/column names differ, adjust accordingly.
2. Querying the Data
You want to:
- Filter
SoldInventoryby date range and store. - For each
SoldInventory, sum:- Cost of Goods Sold:
buying_price * quantity - Revenue:
selling_price * quantity
- Cost of Goods Sold:
- Calculate Net Income: Revenue - Cost of Goods Sold.
Here’s how you can do it efficiently:
use App\Models\SoldInventory;
use Illuminate\Support\Facades\DB;
function getStoreReport($storeId, $startDate, $endDate)
{
$result = DB::table('sold_inventories')
->join('sold_inventory_items', 'sold_inventories.id', '=', 'sold_inventory_items.sold_inventory_id')
->join('inventory_in_stores', 'sold_inventory_items.inventory_in_store_id', '=', 'inventory_in_stores.id')
->where('sold_inventories.store_id', $storeId)
->whereBetween('sold_inventories.date_of_sale', [$startDate, $endDate])
->selectRaw('
SUM(inventory_in_stores.buying_price * sold_inventory_items.quantity) as cost_of_goods_sold,
SUM(inventory_in_stores.selling_price * sold_inventory_items.quantity) as revenue
')
->first();
$costOfGoodsSold = $result->cost_of_goods_sold ?? 0;
$revenue = $result->revenue ?? 0;
$netIncome = $revenue - $costOfGoodsSold;
return [
'costOfGoodsSold' => $costOfGoodsSold,
'revenue' => $revenue,
'netIncome' => $netIncome,
];
}
3. Using in Livewire
In your Livewire component:
public $storeId;
public $startDate;
public $endDate;
public $report = [];
public function generateReport()
{
$this->report = getStoreReport($this->storeId, $this->startDate, $this->endDate);
}
4. Exporting as PDF (DomPDF)
You can use a Blade view for the report and generate a PDF:
use Barryvdh\DomPDF\Facade\Pdf;
public function downloadReport()
{
$data = getStoreReport($this->storeId, $this->startDate, $this->endDate);
$pdf = Pdf::loadView('reports.store_report', compact('data'));
return $pdf->download('store_report.pdf');
}
5. Blade Example (resources/views/reports/store_report.blade.php)
<table>
<tr>
<th>Cost of Goods Sold</th>
<td>{{ number_format($data['costOfGoodsSold'], 2) }}</td>
</tr>
<tr>
<th>Revenue</th>
<td>{{ number_format($data['revenue'], 2) }}</td>
</tr>
<tr>
<th>Net Income</th>
<td>{{ number_format($data['netIncome'], 2) }}</td>
</tr>
</table>
6. Summary
- Use a query with joins and
SUM()to get your totals. - Filter by store and date range.
- Use Livewire for interactivity.
- Use DomPDF to export the report.
If you need to adjust for different column names or relationships, just update the query accordingly.
Let me know if you need help integrating this into your Livewire component or customizing the PDF output!