Search code examples
phplaravellaravel-5laravel-query-builder

How to check if table is already joined in Laravel Query Builder


I created a query. I want to join my table with students table:

$query->leftJoin('students', 'learners.student_id', '=', 'students.id');

But I don't know my table joined before or not. How should I do that?


Solution

  • I found this solution:

    function joined($query, $table) {
        $joins = $query->getQuery()->joins;
        if($joins == null) {
            return false;
        }
        foreach ($joins as $join) {
            if ($join->table == $table) {
                return true;
            }
        }
        return false;
    }
    
     // If not already joined, then join
    if ( !joined($query, 'students') ) {
        $query->leftJoin('students', 'learners.student_id', '=', 'students.id');
    }