Last active
December 16, 2015 18:29
-
-
Save nazieb/5478284 to your computer and use it in GitHub Desktop.
This code below is the example how to apply a global filter for Eloquent Models in Laravel (tested with LV 3.2.14). This will be useful if you have data that is stored in one table but has some classification defined by a column (in this example the column name is 'type') and you want to treat them differently in different models.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class Parents extends Eloquent { | |
| const TYPE_A = 1; | |
| const TYPE_B = 2; | |
| static $type = null; | |
| function __construct($type = null) | |
| { | |
| parent::__construct(); | |
| if(!empty($type)) static::$type = $type; | |
| } | |
| public function __call($method, $parameters) | |
| { | |
| $return = parent::__call($method, $parameters); | |
| if($method == 'query') $return->where('type', '=', static::$type); | |
| return $return; | |
| } | |
| public function save() | |
| { | |
| $this->type = static::$type; | |
| parent::save(); | |
| } | |
| } | |
| class ChildA extends Downloads { | |
| function __construct() | |
| { | |
| return parent::__construct( static::TYPE_A ); | |
| } | |
| } | |
| class ChildB extends Downloads { | |
| function __construct() | |
| { | |
| return parent::__construct( static::TYPE_B ); | |
| } | |
| } | |
| var $childA = new ChildA; | |
| var_dump( $childA::all() ); // will only shows data with "type" = "1" | |
| $childA->column_name = "value"; | |
| $childA->save(); // the "type" column will be set to "1" automatically | |
| var $childB = new ChildB; | |
| var_dump( $childB::all() ); // will only shows data with "type" = "2" | |
| $childB->column_name = "value"; | |
| $childB->save(); // the "type" column will be set to "2" automatically |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment