Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

Global scopes have recently been added :)

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

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

Last updated 2 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.

© 2024 Laravel.io - All rights reserved.