File: /home/armgroup/libs/app/Http/Livewire/Admin/Attribute/Edit.php
<?php
namespace App\Http\Livewire\Admin\Attribute;
use App\Http\Livewire\ConvertEmptyStringsToNull;
use App\Http\Livewire\General;
use App\Models\Attribute;
use App\Models\AttributeValue;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
class Edit extends Component
{
use ConvertEmptyStringsToNull, General;
public Attribute $attribute;
public $attributeGroupId;
public $values = [];
public $deleteIds = [];
public function mount()
{
$this->values = $this->attribute
->values()
->select('id', 'attribute_id', 'value')
->get()
->toArray();
$this->attributeGroupId = $this->attribute->group_id;
}
public function render()
{
return view('livewire.admin.attribute.edit');
}
protected function rules()
{
return ['values.*.value' => 'required|max:250|string|distinct'];
}
protected $validationAttributes = ['values.*.value' => 'مقدار'];
public function addItem()
{
array_push($this->values, [
'id' => null,
'attribute_id' => $this->attribute->id,
'value' => null,
]);
}
public function removeItem($index)
{
if ($this->values[$index]['id']) {
$this->deleteIds[] = $this->values[$index]['id'];
}
unset($this->values[$index]);
}
public function update()
{
$this->validate();
DB::transaction(function () {
if (! count($this->values)) {
$this->attribute->values()->delete();
} else {
if (count($this->deleteIds)) {
AttributeValue::whereIn('id', $this->deleteIds)->delete();
}
AttributeValue::upsert(
$this->values,
['id', 'attribute_id'],
['value']
);
}
saveActivity("مقادیر ویژگی {$this->attribute->name} ویرایش شد", $this->attribute);
$this->doneMessage("مقادیر ویژگی {$this->attribute->name} با موفقیت ویرایش شد");
});
return redirect()->route('admin.attribute-groups.show', $this->attributeGroupId);
}
}