Filter results with ManyToMany relationship in laravel

0

I have 2 tables where there is a relationship, client and content using a pivot table contents_clients , when selecting the contents of client "X" I can know what contents belong to it, but I can not apply a filter referencing a column of table content

$client = Client::find($client_id)->contents;
// Retorna um array de collection com os conteudos

all: [
   App\Content {#795
     id: "76",
     title: "Teste Client 1",
     content: "TESTE",
     client_alteration: null,
     target: "2",
     scheduled_to: "2016-08-30 00:00:00",
     status: "2",
     created_at: "2016-08-29 14:27:34",
     updated_at: "2016-08-29 14:27:34",
     pivot: Illuminate\Database\Eloquent\Relations\Pivot {#794
       client_id: "1",
       content_id: "76",
     },
   },............

How do I apply a filter and select status = 2 ? I already tried: $client = Client::find($client_id)->contents->where('status', 2)->get(); and I get; PHP warning: Missing argument 1 for Illuminate\Support\Collection::get()

    
asked by anonymous 29.08.2016 / 16:43

1 answer

0

Using this way you're firing the collection method , rather than query builder . You could try to chain the where method shortly after receiving a relation, but this would result in a collection of contents and not clients , like this:

$contents = Client::find($id)->contents()->where('contents.status', 2)->get( );

For these situations, you can change the query of an eager loading, like this:

$clients = Client::with(
    [
        'contents' => function ($query) {
            $query->where('contents.status', 2);
        }
    ]
)->get();

Note: Laravel 5.3 version

    
30.08.2016 / 12:49