File: D:/HostingSpaces/SBogers10/shop.komma.nl/app/Properties/Kms/PropertyKeyController.php
<?php
namespace App\Properties\Kms;
use App\Properties\Models\Property;
use App\Properties\Models\PropertyKey;
use App\Properties\Models\PropertyKeyTranslation;
use App\Properties\Models\PropertyValueTranslation;
use App\Properties\Resources\Key;
use App\Properties\Resources\KeyValueTranslation;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Komma\KMS\Core\SectionController;
class PropertyKeyController extends SectionController
{
protected string $slug = "property_keys";
protected string $classModelName = PropertyKey::class;
protected ?string $forTranslationModelName = PropertyKeyTranslation::class;
public function __construct()
{
$section = new PropertyKeySection($this->slug);
parent::__construct($section);
$this->modelService = new PropertyKeyService();
}
public function requiredPropertyKeysForCategories(Request $request, string $category_ids) {
//Get the category ids from the request. category_ids must be a string like this: '1-2-4-8'
$categoryIds = collect(explode('-', $category_ids))->filter(function($item) {
return is_numeric($item);
})->map(function($item) {
return intval($item, 10);
})->toArray();
$propertyKeys = $this->modelService->requiredPropertyKeysForCategories($categoryIds);
return Key::collection($propertyKeys);
}
protected function destroyForModel(Model $model)
{
/** @var $model PropertyKey */
$model->load('properties.key.translations', 'properties.values.translations');
$model->properties()->get()->each(function(Property $property) use($model) {
if($property->key) $property->key->translations()->delete();
PropertyValueTranslation::whereIn('id', $property->values->pluck('id'))->delete();
});
return $model;
}
/**
* This method is called when a item will be deleted
*
* @param Model $model
* @return mixed
* @throws \Exception
*/
public function destroy(Model $model)
{
/** @var PropertyKey $model */
$this->authorize('destroy', $model);
$model = $this->destroyForModel($model);
//We need to delete they keys properties, because a property without a key must not exist.
$model->properties()->with('key.translations', 'values.translations')->get()->each(function(Property $property) {
$property->key->translations()->delete();
PropertyValueTranslation::whereIn('id', $property->values()->pluck('id'))->delete();
$property->values()->delete();
});
//Always delete the propertyKey at the end.
$model->translations()->delete();
$model->delete();
//Return to the item index
return Redirect::action('\\' . get_class($this) . '@index', [])->with('message', __('KMS::global.removed'));
}
}