Hi, everybody.
I have a model named User which contains many groups, to retrieve all students, I can use eloquent query like so:
User::whereGroup('student')->get();
But for clearly code, I want to create another model named Student and extends the User class. How can I append 'whereGroup' to each query so I can get all student by:
Student::all(); // Results same as above statement.
or
Student::count();
Without overriding each eloquent method?
Thanks.
UPDATE Below is example for Laravel4. In Laravel5 method signatures changed a bit, so read this instead http://softonsofa.com/laravel-5-eloquent-global-scope-how-to/
You need global scope for this.
Very basic example (for more check SoftDeletingScope and SoftDeletingTrait):
// Model
class Student extends User {
protected $table = 'users';
public static function boot()
{
static::addGlobalScope(new StudentScope);
}
}
// Scope
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\ScopeInterface;
class StudentScope implements ScopeInterface {
public function apply(Builder $builder)
{
$builder->where('group', '=', 'student');
}
public function remove(Builder $builder) { // you don't need this }
}
Why Global Scope? Is it better to use Query Scope in this case? I'm a bit confused, when do we need to use Global Scope and when we need to use Query Scope.?
jarektkaczyk said:
UPDATE Below is example for Laravel4. In Laravel5 method signatures changed a bit, so read this instead http://softonsofa.com/laravel-5-eloquent-global-scope-how-to/
You need global scope for this.
Very basic example (for more check SoftDeletingScope and SoftDeletingTrait):
// Model class Student extends User { protected $table = 'users'; public static function boot() { static::addGlobalScope(new StudentScope); } }
// Scope use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\ScopeInterface; class StudentScope implements ScopeInterface { public function apply(Builder $builder) { $builder->where('group', '=', 'student'); } public function remove(Builder $builder) { // you don't need this } }
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community