Monday, August 13, 2018

Laravel Models Eloquent Dynamically change table name

Some times you need to use one model for many tables, that means you want the same model but with many tables . So the property table will be dynamically set .to achieve this all you have to do is to use a trait that do the job as shown in the following code:

 

 /* DynamicTable.php */ 
 
trait DynamicTable
{
    protected $connection = null;
    protected $table = null;

    public function bind(string $connection, string $table)
    {
        $this->setConnection($connection);
        $this->setTable($table);
    }

    public function newInstance($attributes = [], $exists = false)
    {
        // Overridden in order to allow for late table binding.

        $model = parent::newInstance($attributes, $exists);
        $model->setTable($this->table);

        return $model;
    }

}


let's say our Model is called Profile :
require_once("DynamicTable.php"); 
 
class Profile extends Illuminate\Database\Eloquent\Model {
 
 use DynamicTable;
 
 public $timestamps = false; 
   
} 
 

Now, when you need to retrieve Model you will create a new object of this model and assign table and connection if the connection is different from default:
profiel1 = new Profile;
prfoile->setTable ("profile01");
profile->setConnection("mysql");
$results = $profile->find(123);

To insert data you can do the same .
Some retrieving commands will not work like all(), but you can use where(1,1) and it will do the job.

No comments:

Post a Comment