Support the ongoing development of →
Database Eloquent
Last updated 2 years ago.

Eloquent can be tricky. You write queries one way which you think makes sense but you then realize there are many ways that make sense. For the way you have it defined, I think this is your approach

$name = "category name";

$cities = App\City::whereHas('rest', function ($query) use($name) {
    $query->category()->where('name', $name);

edit: this might work?

$cities = App\City::all();
$category = $cities->rest()->category()->where('name', $name);

I would also suggest running dd($query->toSql()) for further learning on relationships :]

Last updated 8 years ago.

Thank you I really appreciate it but it didn't work for me. But it gave me an idea and I found another way.

    $category = App\Category::find(1);
    $rests = $category->rest()->where('city_id', '=', '1')->get();

    foreach($rests as $rest){
        echo $rest->name, "<br>";

What do you think about it?


Hey, i thought about another way with HasManyThrough but it didn't work for me for some reasons. so here what i did to solve the problem:

Route::get('food/{city}/{name}', function($city, $name){
    $category = App\Category::where('name', '=', $name)->first();
    $city = App\City::where('name', '=', $city)->first();

    $rests = $category->rest()->where('city_id', '=', $city->id)->get();

    foreach($rests as $rest){
        echo $rest->name, '<br>';

Sign in to participate in this thread!


Your banner here too?

itay012 itay012 Joined 19 Sep 2015


We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 - All rights reserved.