Rev3rse Rev3rse - 6 months ago 26
PHP Question

Laravel 4: How to apply a WHERE condition to all queries of an Eloquent class?

I'm trying to implement an "approved' state for a table I have, it's pretty straightforward, basically, if the row's approve column equals 1; that row should be retrieved, otherwise it shouldn't.

The problem is, now I have to go through the whole codebase and add a WHERE statement(i.e., function call) which is not only time consuming but also inefficient(if I ever want to remove that feature, etc.)

How can I do that? Is it as easy as adding

inside the Eloquent child class' constructor? Wouldn't that affect other CRUD operations? such as not updating an unapproved row?


The closest thing I found is Eloquent query scope.

Even though it requires a minor change in my code(prefixing queries) it still gives me what I'm looking with great flexibility.

Here's an example:

Create a function within the Eloquent child class:

class Post extends Eloquent {

    public function scopeApproved($query)
        return $query->where('approved', '=', 1/*true*/);


Then simply use it like this:

$approvedPosts = Post::approved()-><whatever_queries_you_have_here>;

Works perfectly. No ugly repeated WHERE function calls. easy to modify. Much easier to read(approved() makes much more sense than where('approved', '=', 1) )