Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

abdulrehman176617's avatar

Result from two table in single query in Laravel

#attributes: array:2 [▼
        "id" => 1
        "name" => "Saint Lucia country"
	"city" => array:8 [▼
            0 => App\Models\City {#1449 ▶}
            1 => App\Models\City {#1436 ▶}
            2 => App\Models\City {#1462 ▶}
            3 => App\Models\City {#1475 ▶}
            4 => App\Models\City {#1494 ▶}
            5 => App\Models\City {#1503 ▶}
            6 => App\Models\City {#1509 ▶}
            7 => App\Models\City {#1533 ▶}
      ]

if have country table and city table. I want to get a country and cities related to it in above format how can it do this. I want this result but in single query in Laravel please someone help.

if above format ** id** and name is coming from country table and city is in array format and its coming from city table

0 likes
11 replies
Sinnbeck's avatar

Use eager loading as suggested by @elliott but be aware that it takes two queries, not just one.

Country::with('cities')->find(1);
abdulrehman176617's avatar

@elliott @sinnbeck can't we make it more optimize. I want to make it as optimize as possible.

if have use it but its using 2 queries and calling one time county model and many time city model that not optimize. right ?

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@abdulrehman176617 two queries is good. More than that is bad. In theory you can use a single query with join, but it's a lot of work to get working and most likely won't be faster

2 likes
James_Bhatta's avatar

@abdulrehman176617 Also with custom queries you will have to sacrifice some of the handy features provided by Eloquent. Consider caching data for better performance.

webrobert's avatar

@abdulrehman176617

Unless there is something missing from the question, @sinnbeck already gave you the best answer.

$country = Country::with('cities')->find(1);

dd($country->toArray()); // have a look?
$countries = Country::with('cities')
	->take(5); // and see
	->get();

dd($countries->toArray()); 

🤷🏽‍♂️

2 likes

Please or to participate in this conversation.