File: D:/HostingSpaces/SBogers10/ste.komma.pro/app/Products/ProductService.php
<?php
namespace App\Products;
use App\Base\Service;
use App\Products\Models\Product;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Collection;
final class ProductService extends Service
{
/**
* Base query for get product from DB
*
* @return BelongsToMany
*/
private function baseProductQuery()
{
return Product::where('active', 1)
->with('translation')
->whereHas('translation', function ($q) {
$q->whereNotNull('name')
->where('name','!=', '');
})
->orderBy('lft','asc');
}
/**
* Get all products
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public function getAllProducts()
{
return $this->baseProductQuery()->get();
}
/**
* Get the next products, if no more next, fill in missing ones starting from the first
*
* @param Product $product
* @param int $amount
* @return Collection
*/
public function getNextProducts(Product $product, $amount = 3)
{
$nextProducts = $this->baseProductQuery()
->where('products.id', '!=', $product->id)
->where('products.lft', '>', $product->lft)
->take($amount)
->get();
if($nextProducts->count() >= $amount) return $nextProducts;
$missingProducts = $this->baseProductQuery()
->where('products.id', '!=', $product->id)
->whereNotIn('products.id', $nextProducts->pluck('id')->toArray())
->take($amount - $nextProducts->count() )
->get();
return $nextProducts->merge($missingProducts);
}
}