Hi
Today we will learn how and where to use query scopes.
Some times we are repeating a code snippet or a condition a number of times. Suppose we have to find a list of users who are active and a user which is active. In controller generally we will write
As we can see, the where() condition checks "if active is" repeated twice.
To prevent this, in Laravel, we can use query scopes. Query scopes are single functions that help us reuse the logic in Models. Let’s define a query scope in Model and change the Controller method as follows:
As we can see, we’ve defined a method called scopeActive() in Model, which is prefixed with the word scope and CamelCased. This way, Laravel can understand that it’s a query scope, and we can use that scope directly. As we can see, the conditions in the Controller have also changed. They have changed from where('active', 1) to active().
Thanks
Today we will learn how and where to use query scopes.
Some times we are repeating a code snippet or a condition a number of times. Suppose we have to find a list of users who are active and a user which is active. In controller generally we will write
<?php
class UserController extends BaseController {
// finding list of users who are active.
public function listUsers() {
$users = User::where('active', 1)->get();
}
// finding a user detail which is active.
public function userDetail($id) {
$user = User::where('active', 1)->find($id);
}
}
?>
As we can see, the where() condition checks "if active is" repeated twice.
To prevent this, in Laravel, we can use query scopes. Query scopes are single functions that help us reuse the logic in Models. Let’s define a query scope in Model and change the Controller method as follows:
<?php
//Model File
Class User extends Eloquent {
//We've defined a Query scope called active
public function scopeActive($query) {
return $query->where('active', 1);
}
}
//Controller File
class UserController extends BaseController {
// finding list of users who are active.
public function listUsers() {
$users = User::active()->get();
}
// finding a user detail which is active.
public function userDetail($id) {
$user = User::active()->find($id);
}
}
?>
As we can see, we’ve defined a method called scopeActive() in Model, which is prefixed with the word scope and CamelCased. This way, Laravel can understand that it’s a query scope, and we can use that scope directly. As we can see, the conditions in the Controller have also changed. They have changed from where('active', 1) to active().
Thanks
No comments:
Post a Comment