Ad

Sorting A Polymorphic Relationship Laravel

I have currently set up a poloymorphic relationship by using a views table to represent this and it is working

Whenever I try something like this:

    public function index($id)
    {
        $bar = Bar::find($id);

        echo count($bar->views);
    }

I get the number of results I am expecting and the results are properly viewable with a var_dump as well.

Only when I try to sort the results with a simply where statement like this, I am getting no results at all. I tried multiple where statements but simply nothing happens. No errors.

   public function index($id)
    {
        $bar = Bar::find($id);

        $bar->views->where('id', '=', 1);
    }

Can I not sort the results that I have gotten returned from the polymorphic relationship or I something else going wrong here?

Ad

Answer

The example in the documentation looks very similar with one difference:

$user->posts()->where('active', 1)->get();

So it looks like you might need to:

looks like you might need to:

$bar->views()->where('id', '=', 1); // notice the parentheses after `views`
Ad
source: stackoverflow.com
Ad