File: //home/armgroup/libs/app/Http/Livewire/Admin/AttributeGroup/Create.php
<?php
namespace App\Http\Livewire\Admin\AttributeGroup;
use App\Http\Livewire\ConvertEmptyStringsToNull;
use App\Http\Livewire\General;
use App\Models\AttributeGroup;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Livewire\Component;
class Create extends Component
{
use ConvertEmptyStringsToNull, General;
public $name;
public $label;
public $sort_order;
public $attributes = [];
public $category_id = [];
public $categories;
public function mount()
{
$this->categories = Category::doesntHave('children')
->where('type', Product::class)
->select('id', 'name')
->get();
array_push($this->attributes, [
'name' => null,
'highlight' => false,
'sort_order' => null,
]);
}
public function render()
{
return view('livewire.admin.attribute-group.create');
}
protected function rules()
{
return [
'name' => 'required|max:250|string',
'label' => 'nullable|max:250|string',
'sort_order' => 'nullable|integer|min:0|max:10000',
'attributes.*.name' => 'required|max:250|string|distinct',
'attributes.*.highlight' => 'required|boolean',
'attributes.*.sort_order' => 'nullable|integer|min:0|max:10000',
'category_id.*' => ['required', Rule::exists('categories', 'id')->where(function ($query) {
return $query->where('type', Product::class);
})],
];
}
protected $validationAttributes = [
'attributes.*.name' => 'ویژگی',
'attributes.*.highlight' => 'برجسته',
'attributes.*.sort_order' => 'ترتیپ',
];
public function addItem()
{
array_push($this->attributes, [
'name' => null,
'highlight' => false,
'sort_order' => null,
]);
}
public function removeItem($index)
{
unset($this->attributes[$index]);
}
public function store()
{
$this->validate();
DB::transaction(function () {
$attributeGroup = AttributeGroup::create([
'name' => $this->name,
'label' => $this->label,
'sort_order' => $this->sort_order,
]);
$attributeGroup->attributes()->createMany($this->attributes);
if (count($this->category_id)) {
$attributeGroup->categories()->attach($this->category_id);
}
saveActivity("گروه ویژگی {$this->name} ایجاد شد", $attributeGroup);
$this->doneMessage("گروه ویژگی {$this->name} با موفقیت ایجاد شد");
});
return redirect()->route('admin.attribute-groups.index');
}
}