ldc-volena/app/Http/Controllers/Bo/SectionController.php
2023-11-20 10:51:41 +01:00

112 lines
3.5 KiB
PHP

<?php
namespace App\Http\Controllers\Bo;
use App\Enums\StaticPageType;
use App\Http\Controllers\Controller;
use App\Http\Requests\Bo\Sections\UpdateSectionRequest;
use App\Models\Section;
use App\Models\StaticPage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class SectionController extends Controller
{
/**
* Create the controller instance.
*/
public function __construct()
{
$this->authorizeResource(Section::class);
}
/**
* Display a listing of the resource.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Contracts\View\View
*/
public function index(Request $request): \Illuminate\Contracts\View\View
{
/** @var \Illuminate\Database\Eloquent\Builder $query */
$query = Section::query()->with('page');
// Filter by related page if requested.
if (
$request->related_page &&
null !== StaticPage::where('type', \collect(StaticPageType::all())
->where('name', $request->related_page)->first())->first()
) {
$query = $query->whereBelongsTo(
StaticPage::where(
'type',
\collect(StaticPageType::all())->where('name', $request->related_page)->first()
)->first(),
'page'
);
}
/** @var string $search Search field */
$search = $request->search;
if ($search) {
$this->searchQuery(
$query,
$search,
null,
'h2_title',
);
}
$searchFields = \implode(', ', [
Str::ucfirst(__('validation.custom.h2_title')),
]);
/** Sort columns with a query */
$this->sortQuery($query);
/** Custom pagination */
$sectionModelList = $this->paginate($query);
return view('bo.pages.sections.index', compact('sectionModelList', 'search', 'searchFields'));
}
/**
* Show the form for editing the specified resource.
*
* @param App\Models\Section $section
* @return \Illuminate\Contracts\View\View
*/
public function edit(Section $section): \Illuminate\Contracts\View\View
{
return view('bo.pages.sections.edit', ['sectionModel' => $section]);
}
/**
* Update the specified resource in storage.
*
* @param \App\Http\Requests\Bo\Sections\UpdateSectionRequest $request
* @param \App\Models\Section $section
* @return \Illuminate\Http\RedirectResponse
*/
public function update(UpdateSectionRequest $request, Section $section): \Illuminate\Http\RedirectResponse
{
return DB::transaction(function () use ($request, $section) {
$section->fill(array_replace_recursive(
\json_decode(\json_encode($section->toArray()), true),
$request->validated()
));
if ($section->saveOrFail()) {
return redirect()->route('bo.sections.edit', $section)
->with('success', __('crud.messages.has_been_updated', [
'model' => Str::ucfirst(__('models.classes.section'))
]));
}
return redirect()->route('bo.sections.edit', $section)
->with('error', __('crud.messages.cannot_be_updated', [
'model' => Str::ucfirst(__('models.classes.section'))
]));
});
}
}