Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional join in Laravel Fluent

Tags:

php

laravel

In Laravel PHP framework you can use a condition inside a where clause, like this (Fluent):

...
->where(function($query) use ($var) {
    if(isset($var)) {
        $query->where('something', '=', $var);
    }
})
->...

So if you do not have a $var variable, the where clause will not be added to the query.

I would like to do the same thing, but with a join clause, so for example join with another table only if $var is set, but this does not work, the query collapses:

...
->join('tableB', function($query) use ($var) {
    if(isset($var)) {
        $query->on('tableA.id', '=', 'tableB.id'); 
    }
})
->...

Any suggestion?

like image 245
Balazs Sipos Avatar asked Mar 21 '13 15:03

Balazs Sipos


People also ask

How to use condition in join in Laravel?

In Laravel PHP framework you can use a condition inside a where clause, like this (Fluent): ... ->where(function($query) use ($var) { if(isset($var)) { $query->where('something', '=', $var); } }) ->... So if you do not have a $var variable, the where clause will not be added to the query.

How to add condition in left join in Laravel?

$test = DB::table('table1 AS a') ->leftJoin('table2 AS b', 'a. field2', '=', 'b. field2') ->leftJoin('table3 AS c', function($join){ $join->on('a.

IS NOT NULL laravel?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .


1 Answers

You don't need to chain all methods on a single cast. For instance:

// Instantiates a Query object.
$query = Db::table('posts')->where('published', '=', '1');

// Adds conditional join and where
if (Input::has('category')) {
    $query->join('categories', 'categories.id', '=', 'post.category_id')
        ->where('categories.permalink', '=', Input::get('category'));
}

// Adds another clause
$query->order_by('created_at');

// Fecthes results
$results = $query->get()
like image 78
vFragosop Avatar answered Oct 02 '22 08:10

vFragosop