Reputation: 1526
I come from cakePHP where it is possible to have every get or list query to include a standard where "something = something" in the Model. Per function in the controller this can be ignored, but for all others this is used.
Now I am wondering how to do this in Laravel 5. I would like to add something like below code in the Model or in the Controller (but preferably in the Model):
public function __construct(Page $page) {
$page->where('is_active', 1);
}
So that when running any query on the pages table it will only give me active pages. Except when I manually add where('is_active', 0)
or something else to include all active and inactive pages.
Any help would be very appreciated
Upvotes: 0
Views: 354
Reputation: 277
Most of what you want can be achieved by using a query scope on the model.
You'd put something like this in your model:
/**
* Scope a query to only include active users.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeActive($query)
{
return $query->where('active', 1);
}
And then when you wanted to use it you'd do something like this:
$users = App\User::active()->orderBy('created_at')->get();
It doesn't set a default for all queries, but it might be a better long term solution. Docs are here: http://laravel.com/docs/5.1/eloquent#query-scopes
Upvotes: 2