Skip to content

Instantly share code, notes, and snippets.

@goranprijic
Created December 17, 2014 10:12
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save goranprijic/c578acb0086e8cd85179 to your computer and use it in GitHub Desktop.
Save goranprijic/c578acb0086e8cd85179 to your computer and use it in GitHub Desktop.
Check if table is already joined in Laravel Query Builder
<?php
class BaseModel extends Eloquent {
public static function isJoined($query, $table)
{
$joins = $query->getQuery()->joins;
if($joins == null) {
return false;
}
foreach ($joins as $join) {
if ($join->table == $table) {
return true;
}
}
return false;
}
}
@tormit
Copy link

tormit commented Jul 30, 2015

Thank you for this great script.

@franzose
Copy link

Thanks for the solution.

@CaptainHypertext
Copy link

Awesome

@smilekomiya
Copy link

Thanks a lot.

@BadChoice
Copy link

BadChoice commented Jun 12, 2017

You can use the collections to simplify it a bit

public static function isJoined($query, $table){
    $joins = collect($query->getQuery()->joins);
    return $joins->pluck('table')->contains($table);
}

@arnoudhgz
Copy link

Yes and avoid the temporary variable also :)

return collect($query->getQuery()->joins)->pluck('table')->contains($table);

@Soulriser
Copy link

Thanks for this @goranprijic, and to @BadChoice and @arnoudhgz for the optimizations. I'm using Eloquent separate from Laravel, so I use the make() method on the Collection class directly:

$isJoined = Collection::make($query->getQuery()->joins)->pluck('table')->contains($table);

@carltondickson
Copy link

carltondickson commented Jul 23, 2018

->contains can also be a callback function. I had to use this as my joined table wasn't just a table name but instead an alias, something like table_name AS permissions_table.

return collect($query->getQuery()->joins)->pluck('table')->contains(function ($value, $key) use ($table) {
    if (is_a($value, Illuminate\Database\Query\Expression::class)) {
        /** @var Illuminate\Database\Query\Expression $value */
        return $value->getValue() === $table; // $table is something like "table_name AS permissions_table"
    }

    return $value === $table;
});

@Soulriser
Copy link

Soulriser commented Mar 21, 2019

Just throwing in another possible solution that uses native php array functions and thus should have better performance:

return array_search($table, array_column((array)$builder->getQuery()->joins, 'table'));

Be sure to explicitly check the return value for false using ===.

@AeonFr
Copy link

AeonFr commented Mar 26, 2019

Thanks for this snippet, very useful

This method detects all kinds of joins (leftJoin(), join(), etc.)

Clarifying just in case someone else was wondering!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment