4

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.

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.