Files
investbrain/app/Http/Controllers/PortfolioController.php
T

65 lines
2.0 KiB
PHP
Raw Normal View History

2024-08-05 22:41:53 -05:00
<?php
namespace App\Http\Controllers;
2024-08-21 20:42:32 -05:00
use App\Models\Holding;
2024-08-05 22:41:53 -05:00
use App\Models\Portfolio;
2024-10-22 16:48:53 -05:00
use Illuminate\Http\Request;
2024-08-05 22:41:53 -05:00
class PortfolioController extends Controller
{
/**
* Show the form for creating a new resource.
*/
public function create()
{
return view('portfolio.create');
}
/**
* Display the specified resource.
*/
2024-10-22 16:48:53 -05:00
public function show(Request $request, Portfolio $portfolio)
2024-08-05 22:41:53 -05:00
{
2024-10-22 16:48:53 -05:00
if ($request->user()->cannot('readOnly', $portfolio)) {
abort(403);
}
2024-08-28 22:06:47 -05:00
$portfolio->load(['transactions', 'holdings']);
2024-08-21 20:42:32 -05:00
// get portfolio metrics
$metrics = cache()->remember(
2024-08-21 20:42:32 -05:00
'portfolio-metrics-' . $portfolio->id,
60,
function () use ($portfolio) {
2024-08-28 22:06:47 -05:00
return Holding::query()
->portfolio($portfolio->id)
2024-08-29 18:46:21 -05:00
->withPortfolioMetrics()
2024-08-28 22:06:47 -05:00
->first();
2024-08-21 20:42:32 -05:00
}
);
$formattedHoldings = $this->getFormattedHoldings($portfolio);
2024-08-21 20:42:32 -05:00
return view('portfolio.show', compact(['portfolio', 'metrics', 'formattedHoldings']));
}
public function getFormattedHoldings($portfolio)
{
$formattedHoldings = '';
foreach($portfolio->holdings as $holding) {
$formattedHoldings .= " * Holding of ".$holding->market_data->name." (".$holding->symbol.")"
."; with ". ($holding->quantity > 0 ? $holding->quantity : 'ZERO') . " shares"
."; avg cost basis ". $holding->average_cost_basis
."; curr market value ". $holding->market_data->market_value
."; unrealized gains ". $holding->market_gain_dollars
."; realized gains ". $holding->realized_gain_dollars
."; dividends earned ". $holding->dividends_earned
."\n\n";
}
return $formattedHoldings;
2024-08-05 22:41:53 -05:00
}
}