File: D:/HostingSpaces/SBogers10/honger.komma.pro/app/KommaApp/Posts/PostService.php
<?php
namespace App\KommaApp\Posts;
use App\KommaApp\Posts\Models\Post;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class PostService
{
private $today;
/**
* PostService constructor.
*/
public function __construct()
{
$this->today = Carbon::now()->addHour();
$this->today = $this->today->format('Y-m-d H:i:s');
}
/**
* Get all posts from the database
*
* @param bool $pagination
* @param int $itemsPerPage
* @return Collection
*/
public function all($pagination = true, $itemsPerPage = 9)
{
$posts = \App::getSite()
->posts()
->with('translation', 'images', 'categories')
->where('active', 1)
->where('date', '<=', $this->today)
->orderBy('date','desc')
->orderBy('created_at', 'desc');
if($pagination) return $posts->paginate($itemsPerPage);
return $posts->get();
}
/**
* Get all non-featured posts from a Collection|LengthAwarePaginator
*
* @param Collection|LengthAwarePaginator $posts
* @return Collection
*/
public function nonFeatured($posts)
{
return $posts->where('featured',0);
}
/**
* Get all featured posts from a Collection|LengthAwarePaginator
*
* @param Collection|LengthAwarePaginator $posts
* @return Collection
*/
public function featured($posts)
{
return $posts->where('featured',1)
->take(3);
}
/**
* @param Post $post
* @return \Illuminate\Support\Collection
*/
public function relatedPosts(Post $post)
{
// Create collection to return
$relatedPosts = collect();
// Get categories from post which we will relate to
$categories = $post->categories;
// Loop through categories
foreach($categories as $category)
{
$postsInCategory = Post::with('translation','categories')->whereHas('categories', function($query) use($category)
{
$query->where('categories.id', $category->id);
})->get();
// Merge related posts with posts in category
$relatedPosts = $relatedPosts->merge($postsInCategory);
}
// Make sure the collection doesn't contain duplicates
$relatedPosts = $relatedPosts->unique()->take(3);
$relatedPosts = $relatedPosts->keyBy('id');
return $relatedPosts->forget($post->id);
}
}