Laravel 5.2 subquery - filter rows by polymorphic pivot table last row
<p>I've been stuck on this for a few days now and wondering if anyone can help.</p>

<p>DB tables:
'pages', 'statuses', 'status_assignments'</p>

<p>Page model:</p>

<pre><code>protected $appends = ['status'];

public function statuses()
{
    return $this-&gt;morphToMany('App\Models\Status', 'statusable', 'status_assignments')-&gt;withPivot('id', 'assigned_by_user_id', 'locked')-&gt;withTimestamps();
}

public function getStatusAttribute()
{
    return $this-&gt;statuses()-&gt;orderBy('pivot_id', 'DESC')-&gt;first();
}

public function scopeWithStatus($query, $statuses)
{
    $query-&gt;with('statuses');

    if(is_array($statuses) &amp;&amp; count($statuses) &gt; 0)
    {
        $query-&gt;whereHas('statuses', function($q) use($statuses)
        {
            $cs = $q-&gt;orderBy('pivot_id', 'DESC')-&gt;first();
            foreach($statuses as $status) $q-&gt;where('id', $status)-&gt;where('pivot_id', $cs-&gt;pivot-&gt;id);
        });
    }

    return $query;
}
</code></pre>

<p>Status Model:</p>

<pre><code>public function pages()
{
    return $this-&gt;morphedByMany('App\Models\Page', 'categorizable', 'category_assignments')-&gt;withTimestamps();
}
</code></pre>

<p>What I'm trying to do is retrieve a list of pages where the latest status assigned has id of ['array_of_status_ids'] ('$statuses' in scopeWithStatus)</p>

<pre><code>$pages = Page::withStatus([1,2,3,4])-&gt;get();
</code></pre>

<p>Any ideas on this would be gratefully received! Thanks in advance, Kris.</p>