Refactor Brand, Category, and Product controllers to use createWithProps and updateWithProps methods for improved property synchronization
This commit is contained in:
@@ -7,10 +7,30 @@ use App\Domains\Prop\Models\Prop;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use LogicException;
|
||||
|
||||
trait Propable
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $attributes
|
||||
* @param array<string, mixed> $props
|
||||
* @return static
|
||||
*/
|
||||
public static function createWithProps(array $attributes, array $props = []): static
|
||||
{
|
||||
/** @var static $model */
|
||||
$model = DB::transaction(function () use ($attributes, $props): Model {
|
||||
/** @var static $createdModel */
|
||||
$createdModel = static::query()->create($attributes);
|
||||
$createdModel->syncPropValues($props);
|
||||
|
||||
return $createdModel;
|
||||
});
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
@@ -70,6 +90,20 @@ trait Propable
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $attributes
|
||||
* @param array<string, mixed> $props
|
||||
*/
|
||||
public function updateWithProps(array $attributes, array $props = []): static
|
||||
{
|
||||
DB::transaction(function () use ($attributes, $props): void {
|
||||
$this->update($attributes);
|
||||
$this->syncPropValues($props);
|
||||
});
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function deletePropValue(Prop|string $prop): bool
|
||||
{
|
||||
$resolvedProp = $this->resolveProp($prop);
|
||||
|
||||
Reference in New Issue
Block a user