Al_
Al_

Reputation: 2509

laravel using query builder without chaining

I have a query builder that works:

        $article = Page::where('slug', '=', $slug)
                     ->where('hide', '=', $hidden)
                     ->first();

But I want to only add the second where statement if hidden is equal to 1. I've tried the code below which shows the logic of what I'm trying to do, but it doesn't work.

$article = Page::where('slug', '=', $slug);
if ($hidden == 1) {
    $article->where('hide', '=', 1);
}
$article->first();

I'm using Laravel 4, but I think the question still stands with Laravel 3.

Upvotes: 4

Views: 2300

Answers (1)

Oddman
Oddman

Reputation: 3959

Yeah there's a little "gotcha" with Eloquent and the query builder. Try the code below ;)

$query = Page::where('slug', '=', $slug);

if ($hidden == 1) {
    $query = $query->where('hide', '=', 1);
}

$article = $query->first();

Note the assigning of $query within the conditional. This is becuase the first where (statically called) returns a different object to the query object within the conditional. One way to get around this, I believe due to a recent commit, is like so:

$query = Page::where('slug', '=', $slug)->query();

This will return the query object and you can do what you want as per normal (Instead of re-assigning $query).

Hope that helps.

Upvotes: 8

Related Questions