Skip to content
Snippets Groups Projects
ChangeValue.php 1.54 KiB
Newer Older
Shizuco's avatar
Shizuco committed
<?php

namespace App\Nova\Actions;

use App\Models\Product;
Shizuco's avatar
Shizuco committed
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\ActionFields;
use Laravel\Nova\Http\Requests\NovaRequest;

class ChangeValue extends Action
{
    use InteractsWithQueue, Queueable;

    public ?string $field;
    public ?string $retailer;

    public function __construct(?string $field, ?string $retailer)
    {
        $this->field = $field;
        $this->retailer = $retailer;
    }

Shizuco's avatar
Shizuco committed
    public function handle(ActionFields $fields, Collection $models)
    {
        if (!$this->isNotExistSameSKUOnDifferentRetailers($models)) {
Shizuco's avatar
Shizuco committed
            return Action::danger('You chose too much products with the same sku!');
        }
        foreach ($models as $model) {
            Product::where('retailer_id', $this->retailer)->where('sku', $model['sku'])->update([$this->field => $model[$this->field]]);
Shizuco's avatar
Shizuco committed
        }
        return Action::redirect('/');
Shizuco's avatar
Shizuco committed
    }

    /**
     * Get the fields available on the action.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @return array
     */
    public function fields(NovaRequest $request)
    {
        return [];
    }

    private function isNotExistSameSKUOnDifferentRetailers(Collection $models)
    {
Shizuco's avatar
Shizuco committed
        $sku = [];
        foreach ($models as $model) {
Shizuco's avatar
Shizuco committed
            array_push($sku, $model['sku']);
        }
        $result = (count($sku) === count(array_unique($sku)));
        return ($result) ? true : false;
    }
}