Skip to content

Instantly share code, notes, and snippets.

@nazieb
Last active December 16, 2015 18:29
Show Gist options
  • Select an option

  • Save nazieb/5478284 to your computer and use it in GitHub Desktop.

Select an option

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.
<?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