Skip to content

Example Composer

Kelly Mears edited this page Jul 3, 2019 · 1 revision
<?php

namespace App\Composers;

use Roots\Acorn\View\Composer;

use \App\Models\Post;

class RelatedPosts extends Composer
{
    /**
     * List of views served by this composer.
     *
     * @var array
     */
    protected static $views = [
        'partials.content*',
    ];

    /**
     * Data to be passed to view before rendering.
     *
     * @param  array $data
     * @param  \Illuminate\View\View $view
     * @return array
     */
    public function with($data, $view)
    {
        $this->currentPost = get_post(get_the_id());
        $this->postDate = date($this->currentPost->post_date);

        return [
            'randomPosts'     => $this->randomPosts(),
            'nextPost'        => $this->nextPost(),
            'previousPost'    => $this->previousPost(),
            'relatedPosts'    => $this->relatedPosts(),
        ];
    }

    /**
     * Returns random posts
     * @return \Illuminate\Support\Collection
     */
    public function randomPosts()
    {
        return self::published()
            ->orderByRaw('RAND()')
            ->where('id', '!=', $this->currentPost->ID)
            ->take(3)
            ->get();
    }

    /**
     * Returns related posts
     * @return \Illuminate\Support\Collection
     */
    public function relatedPosts()
    {
        return self::published()
                ->orderByRaw('RAND()')
                ->take(3)
                ->get();
    }

    /**
     * Returns published posts
     * @return \Illuminate\Support\Collection
     */
    public static function published()
    {
        return Post::ofType('post')
                ->ofStatus('publish')
                ->with('meta')
                ->with('author');
    }

    /**
     * Returns next post
     * @return \Illuminate\Support\Collection
     */
    public function nextPost()
    {
        return self::published()
                ->where('post_date', '>', $this->postDate)
                ->take(1)
                ->get(['post_title', 'post_name'])
                ->first();
    }

    /**
     * Returns previous post
     * @return \Illuminate\Support\Collection
     */
    public function previousPost()
    {
        return self::published()
                ->where('post_date', '<', $this->postDate)
                ->take(1)
                ->get(['post_title', 'post_name'])
                ->first();
    }
}
Clone this wiki locally