0

How to filter output that chain ( with and where ) function. Bottom output is wwithout chain with where chain. cause it return error if chain with where.Bottom ouput return 2 person with different job. i need to filter the job by Artist. each model person, job and media using relationship belongsToMany. So there're 2 junction table.

[
    {
        "person_id": 1,
        "first_name": "suzuki",
        "last_name": "amanda"
    }
][]

Tables

media
people
media_people
jobs
person_jobs

Controller

    $comics = Media::where('type_id', 3)->get();

    foreach( $comics as $comic )
    {
        $artists = $comic->people()->whereHas('jobs', function( $query ){
            $query->where('job_name', '=', 'Artist');
        })->get();
        
        //json output above without index access
        echo json_encode($artists, JSON_PRETTY_PRINT);

        // but as output result like 2 array. the last one is empty. i try 
        access with index. It return suzuki with error undefined array index 
        0
        echo json_encode($artists[0]->first_name, JSON_PRETTY_PRINT);
    }
david stephen
  • 329
  • 4
  • 12
  • 2
    Does this answer your question? [Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?](https://stackoverflow.com/questions/30231862/laravel-eloquent-has-with-wherehas-what-do-they-mean) – Clément Baconnier Apr 12 '21 at 11:21
  • @ClémentBaconnier yes, chain with whereHas. but it returning empty array with result. `[ { "person_id": 1, "first_name": "suzuki", "last_name": "amanda" } ][]`. when i try to acces by index `$artists[0]->first_name`. it return result `Suzuki` and with error. `Undefined array key 0`. as A error thrown. i try to access without index. `$artists->first_name`. It throw error `property first_name is not exist`. I even chain with toArray . i though is because a collection. same result. – david stephen Apr 12 '21 at 11:47
  • Can you update your question with what have tried ? – Clément Baconnier Apr 12 '21 at 11:51
  • @ClémentBaconnier i edit already result json, and the controller echo section. – david stephen Apr 12 '21 at 11:59

2 Answers2

1

Based on your controller, you can do this

$artist = Media::where('type_id', 3)->get();
$artist = $comics->people()->with(['jobs' => function ($query) {
    $query->where('job_name', 'Artist');
}])->get();

Docs

Localhousee
  • 887
  • 1
  • 5
  • 17
1

By doings so you will get a collection of Comic but it seems you're interested to get a collection of Artist. Here's what I suggest.

 $artists = People::with(['jobs', 'comics'])
                    ->whereHas('jobs', function($q) {
                        $q->where('job_name', 'Artist')
                    })
                     ->whereHas('comics', function($q) {
                        $q->where('type_id', 3)
                    })
                    ->get();
    
    echo json_encode($artists, JSON_PRETTY_PRINT);
Clément Baconnier
  • 5,718
  • 5
  • 29
  • 55