HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/slenders/slenders.nl/app/Komma/MonthlyMustHaves/MonthlyMustHaveService.php
<?php


namespace App\Komma\MonthlyMustHaves;


use App\Komma\Base\Service;
use App\Komma\Categories\Models\Category;
use App\Komma\MonthlyMustHaves\Models\MonthlyMustHave;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;

final class MonthlyMustHaveService extends Service
{

    private $today;

    public function __construct()
    {
        $this->today = now()->endOfDay();
        $this->today = $this->today->format('Y-m-d H:i:s');
        parent::__construct();
    }

    /**
     * Base query
     *
     * @return MonthlyMustHave|\Illuminate\Database\Eloquent\Builder
     */
    private function baseMonthlyMustHaveQuery()
    {
        return MonthlyMustHave::with('translation', 'images')
            ->where('active', 1)
            ->where('date', '<=', $this->today)
            ->orderBy('date','desc')
            ->orderBy('created_at', 'desc');
    }

    /**
     * Get all monthlyMustHaves
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function getMonthlyMustHaves()
    {
        return $this->baseMonthlyMustHaveQuery()->get();
    }

    /**
     * Get $amount of latest monthlyMustHaves
     *
     * @param  int  $amount
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
     */
    public function getLatestMonthlyMustHave($amount = 1)
    {
        return $this->baseMonthlyMustHaveQuery()
            ->take($amount)
            ->get();
    }

    /**
     * Load a collection of MMHs for each category
     *
     * @return Collection
     */
    public function getLatestMonthlyMustHaveForEachCategory()
    {

        $categories = Category::all();

        $mmhs = Collection::make();

        foreach ($categories as $category) {

            $mmh = $category->monthlyMustHaves()
                ->orderBy('date', 'DESC')
                ->where('active', 1)
                ->where('date', '<=', $this->today)
                ->first();

            if(!isset($mmh)) continue;

            $mmh->setRelation('category', $category);
            $mmhs->push($mmh);
        }

        $mmhs->load('translation', 'images');

        return $mmhs;
    }

}