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

jank's avatar
Level 1

Query Builder: multiple joins based on array

Hi everyone,

according to the official documentation I have to write something like this when I want to join multiple tables:

$items = DB::table ( $table ) -> leftJoin ($jointable1', $key1, '=', $joinkey1) -> leftJoin ($jointable2', $key2, '=', $joinkey2) -> leftJoin ($jointable3', $key3, '=', $joinkey3) -> leftJoin ($jointable4', $key4, '=', $joinkey4)

Is it also possible to add the joins by iterating over an array like in ->select () or ->where ()? This would be quite handy if I want to create a query based on a configuration file or something like that. Right now I have to write the query and the joins over and over again when I need them in multiple places.

0 likes
6 replies
bugsysha's avatar

If I understand the question, then the answer is, Yes.

jank's avatar
Level 1

Thanks for the reply. What do I have to write to achieve this? Because something like this is not working:

$leftjoins = [

[$jointable1, $key1, '=', $joinkey1],

[$jointable2, $key2, '=', $joinkey2],

[$jointable3, $key3, '=', $joinkey3],

[$jointable4, $key4, '=', $joinkey4]

];

$items = DB::table ( $table ) -> leftJoin ($leftjoins)

Error: Too few arguments to function Illuminate\Database\Query\Builder::leftJoin(), 1 passed in [...] at least 2 expected.

bugsysha's avatar

You have to loop over $leftJoins and add statements to the builder.

$builder = DB::table($table);

foreach($leftJoins as $leftJoin) {
	$builder->leftJoin(...$jeftJoin);
}

$results = $builder->get();
1 like
jank's avatar
Level 1

Great! That is exactly what I was looking for. Thank you very much!

bugsysha's avatar

You can create some function for that to avoid repetition.

bugsysha's avatar

@jank if that is solution, please mark it as best answer. Thanks.

Please or to participate in this conversation.