File: /var/www/ipsremont-demo/app/Http/Controllers/CurrencyController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\Currency\CreateRequest;
use App\Http\Requests\Currency\IndexRequest;
use App\Http\Requests\Currency\UpdateRequest;
use App\Models\Currency;
use App\Models\CurrencyRateHistory;
use App\Models\Permission;
use App\Models\Region;
use App\Repository\Currency\CurrencyRepository;
use App\Traits\GridTrait;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
class CurrencyController extends Controller
{
use GridTrait;
protected string $permission = Permission::currencies;
protected CurrencyRepository $repository;
public function __construct()
{
parent::__construct();
$this->repository = new CurrencyRepository();
}
public function index(IndexRequest $request): View
{
$data = $this->repository->search($request);
$columns = Currency::columns();
return view('currencies.list', (compact('data', 'columns')));
}
public function create(): View
{
$model = new Currency();
$validate = new CreateRequest();
return view('currencies.create', compact('model', 'validate'));
}
public function store(CreateRequest $request): RedirectResponse
{
$currency = $this->repository->save($request);
$this->repository->addToHistory($currency->id, $currency->rate);
return redirect()->route('currencies.index')->with(['messageSuccess' => __('currencies.messageCreate')]);
}
public function edit(int $id)
{
$model = CurrencyRepository::getById($id);
if (!is_object($model)) {
return redirect()->route('currencies.index')->with(['messageSuccess' => __('currencies.CurrencyNotFound')]);
}
$validate = new UpdateRequest();
$history = CurrencyRateHistory::query()->where('currency_id', $id)->orderBy('created_at', 'desc')->get();
return view('currencies.edit', compact('model', 'validate', 'history'));
}
public function update(UpdateRequest $request): RedirectResponse
{
/** @var Currency $currency */
$currency = Currency::query()->find($request->id);
$oldRate = $currency->rate;
$currency->fill($request->all())->update();
if ($oldRate != $request->rate) {
$this->repository->addToHistory($request->id, $request->rate);
}
return redirect()->route('currencies.index')->with(['messageSuccess' => __('currencies.messageUpdate')]);
}
public function delete(int $id): RedirectResponse
{
$linkedRegions = Region::query()->where('currency_id', $id)->get();
if (!$linkedRegions->isEmpty()) {
return redirect()->route('currencies.index')->with(['messageError' => __('currencies.canNotDeleteMessage')]);
}
$this->repository->delete($id);
return redirect()->route('currencies.index')->with(['messageSuccess' => __('currencies.messageDelete')]);
}
}