Support the ongoing development of Laravel.io →
Database Eloquent

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.

Last updated 3 years ago.
0

Global scopes have recently been added :)

Last updated 3 years ago.
0

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 }
}
Last updated 3 years ago.
0

Thanks, @pmall and @jarektkaczyk, you both helped me too much :)

Last updated 3 years ago.
0

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 }
}
0

Sign in to participate in this thread!

Eventy

Your banner here too?

strevery strevery Joined 15 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.