Alexander Beyer
Alexander Beyer

Reputation: 197

Conditional Join Eloquent

I have been looking through multiple question on stack overflow and also in the eloquent documents and I cannot seem to find how to join a table only if a variable is true.

I have my eloquent query.

$test = false;
$orderBy = 'name'; // Default order by
$sortBy = 'asc'; // Default sort by
$wheres[] = ['is_deleted', '=', $is_deleted];

Comm::where($wheres)
      ->select($selects)
      ->join('div', function($join) use($test) {
            if($test) {
                 $join->on('Comm.div_id', '=', 'div.div_id')
            }
        }
      ->orderBy($orderBy, $sortBy)
      ->paginate($per_page, '*', 'page', $page);

Now I know you can join using the document join methods like

->join('div', 'comm.div_id', '=', 'div.div_id')

Is there anyway to accomplish the conditional add I am trying to do? This is for an api and I want the user to be able to specify if they want certain tables included in the returns results. I havent been able to find a post about this type of functionality. When I run my example code with the test if statement i get an error of:

Parse error: syntax error, unexpected '}'

Upvotes: 1

Views: 2133

Answers (1)

Alexander Beyer
Alexander Beyer

Reputation: 197

So after a while of trial and error, I found you can use conditional clauses to help with joining tables.

$comm = Comm::select($selects)
              ->when($useJoins, function($query) use ($withs) {
                  return $query->with($withs);
              }) 
              ->orderBy($orderBy, $sortBy)
              ->paginate($per_page, '*', 'page', $page);

I'm leaving this here for future reference since there is not a very large amount of data for this type of joining. I have also tried it with the eloquent join methods and those also work I just left it in an array for the with for display purposes.

Upvotes: 4

Related Questions