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

namespace App\Nova\Actions;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Collection;
use Laravel\Nova\Actions\Action;
use App\Models\Product;
use Illuminate\Support\Facades\Cache;
use Laravel\Nova\Fields\ActionFields;
use Laravel\Nova\Http\Requests\NovaRequest;

class ChangeValue extends Action
{
    use InteractsWithQueue, Queueable;

    /**
     * Perform the action on the given models.
     *
     * @param  \Laravel\Nova\Fields\ActionFields  $fields
     * @param  \Illuminate\Support\Collection  $models
     * @return mixed
     */
    public function handle(ActionFields $fields, Collection $models)
    {
        if(!$this->isNotExistSameSKUOnDifferentRetailers($models))
        {
            return Action::danger('You chose too much products with the same sku!');
        }
        $compare = Cache::pull('compare');
        foreach($models as $model)
        {
            Product::where('retailer_id', $compare['retailer'])->where('sku', $model['sku'])->update([$compare['field'] => $model[$compare['field']]]);
        }
    }

    /**
     * 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){
        $sku = [];
        foreach($models as $model)
        {
            array_push($sku, $model['sku']);
        }
        $result = (count($sku) === count(array_unique($sku)));
        return ($result) ? true : false;
    }
}