Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 388
Al_ Avatar asked Feb 17 '23 15:02

Al_


1 Answers

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.

like image 80
Oddman Avatar answered Feb 26 '23 21:02

Oddman