App\Http\Controllers\ProductsGroupController::destroy PHP Method

destroy() public method

Remove the specified resource from storage.
public destroy ( integer $id ) : Response
$id integer
return Response
    public function destroy($id)
    {
        $group_id = false;
        $id = explode('_', $id);
        $view = $id[1];
        $id = $id[0];
        $deleteAll = $view == $id;
        $product = Product::select('id', 'products_group')->with(['group' => function ($query) {
            $query->select('id', 'products_group');
        }])->find($id);
        //is necesary re make the actual group before add to new one because is the principal product of the last one
        if ($product->products_group == $id && count($product->group) > 1) {
            $newPrincipal = Product::select('id')->where('products_group', $id)->where('id', '<>', $id)->first();
            $group_id = $newPrincipal->id;
            Product::where('products_group', $id)->update(['products_group' => $group_id]);
        }
        $product->products_group = null;
        $product->save();
        return json_encode(['deleteAll' => $deleteAll ? true : false, 'message' => trans('product.product_was_deleted_from_this_group')]);
    }
ProductsGroupController