Laravel using a non-binding query builder

I have a query builder that works:

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

But I just want to add a second where statement, if hidden is 1. I tried the code below that 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 am using Laravel 4, but I think the question is still with Laravel 3.

+4
source share
1 answer

Yes, there is a little "gotcha" with Eloquent and a query builder. Try the code below;)

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

Note the purpose of the $ request in the conditional expression. This is because the first is where (statically called) returns another object to the request object in a conditional expression. One way around this, I believe, due to a recent commit, looks like this:

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

This will return the request object, and you can do what you want according to normal (instead of re-assigning the request $).

Hope this helps.

+8
source

All Articles