Balazs Sipos
Balazs Sipos

Reputation: 177

Conditional join in Laravel Fluent

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?

Upvotes: 5

Views: 8702

Answers (1)

vFragosop
vFragosop

Reputation: 5773

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()

Upvotes: 11

Related Questions