File: D:/HostingSpaces/Eurotools/euro-tools.nl/app/KommaApp/Shop/Categories/CategoryService.php
<?php
namespace App\KommaApp\Shop\Categories;
use App\KommaApp\Kms\Core\Kms;
use App\KommaApp\Shop\Categories\Kms\CategorizableInterface;
use App\KommaApp\Shop\Categories\Models\Category;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
class CategoryService
{
/**
* Fetch translated page routes
*
* @return object | bool
*/
public function getAllCategories()
{
$categories = $categories = Category::where('lft',1)
->with('translations')
->first()
->findChildren();
// Find all pages
if( !$categories
) return \App::abort(404);
return $categories;
}
/**
* Get page by specific code name
*
* @param $codeName
* @return Category
*/
public function getCategoryByCodeName($codeName): Category
{
if(!$category = Category::where('code_name','=', $codeName)
->with('translation')
->where('active', 1)
->first()) \App::abort(404);
return $category;
}
/**
* Get page by specific code name
*
* @param $id
* @return Category
*/
public function getCategoryById($id): Category
{
if(!$category = Category::where('id','=', $id)
->with('translation')
->where('active', 1)
->first()) \App::abort(404);
return $category;
}
/**
* @param CategorizableInterface $categorizable
* @param string $categoryName
* @param null $limit
* @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection|static[]
*/
public function getRelatedCategorizablesForCategoryName(CategorizableInterface $categorizable, string $categoryName, int $limit = null)
{
//Try to find a relation name depending on the class name of the categorizable
//If the categorizable classname is something like this App\Some\Product then the relation name would be products
$relationName = str_plural(Kms::getShortNameFromClass($categorizable, true));
/** @var Category $category */
$categoryQuery = Category::whereHas('translations', function(Builder $query) use ($categoryName) {
$query->where('name', '=', $categoryName);
})->with('translations', $relationName.'.images', $relationName.'.translation', $relationName.'.categories');
$category = $categoryQuery->first();
if(!$category) return new Collection();
if(!method_exists($category, $relationName)) {
throw new \RuntimeException('Cannot get related "'.$relationName.'" from a category which has a translation with a name value of "'.$categoryName.'". Since the '.$relationName.' method does not exist');
}
if($limit) $relatedCategorizables = $category->$relationName()->limit($limit)->get();
else $relatedCategorizables = $category->$relationName;
return $relatedCategorizables;
}
}