user2744115
user2744115

Reputation: 82

Laravel 5.1 global scopes... Where should I go?

Well, I've started with Laravel just a few weeks ago, so sorry if I'm repeating something obvious but... here's the thing:

I've got a couple of query scopes in a Photo model:

public function scopeSkipFirst($query) 
{
    return $query->where('id', '>', 1);
}

public function scopeSearch($query, $search) 
{
    return $query->where('title', 'LIKE', "%$search%");
}

Now, I want the first one to be executed everytime I make an Eloquent query by that model, like in Photo::all(); and I want the second query scope to be available to any other model.

What's the best practice way to do this? Are both scenarios global scopes? I've been reading a few posts (like this one), but I have no clear ideas about which documentation should I refer (Laravel's 4.2 # Global scopes section; 5.1 Eloquent's # Events; ¿?).

Upvotes: 0

Views: 1147

Answers (1)

Martin Bean
Martin Bean

Reputation: 39389

If you want all of your models to have a scopeSearch() method, then it would make sense to move it to a trait and then apply that trait to your models. Something like Searchable:

trait Searchable
{
    public function scopeSearch($query, $search) 
    {
        return $query->where($this->getSearchField(), 'LIKE', "%$search%");
    }

    protected function getSearchField()
    {
        return 'title';
    }
}

I’ve also made the column configurable as not all models may have a title column. For example, when I create an Article model in my applications I’ll have a headline column instead of title.

With the above trait, you can make a model searchable by implementing the trait:

class Photo extends Model
{
    use Searchable;
}

You don’t want to make it a global scope. Global scopes are applied to every query. Not every query is going to be a search query, and there also won’t be anything to pass as a search query.

The scopeSkipFirst() method, could be made a global scope if you wanted that to apply any time you queried your Photo model, but I can’t think of a reason why you would want to always skip a particular record. Why have it in the database if you never want to display it?

Upvotes: 5

Related Questions