How to Dynamically Set Table Name in Eloquent Model

How to dynamically set table name in Eloquent Model

The following trait allows for passing on the table name during hydration.

trait BindsDynamically
{
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;
}

}

Here is how to use it:

class ProductLog extends Model
{
use BindsDynamically;
}

Call the method on instance like this:

public function index() 
{
$productLog = new ProductLog;

$productLog->setTable('anotherTableName');

$productLog->get(); // select * from anotherTableName

$productLog->myTestProp = 'test';
$productLog->save(); // now saves into anotherTableName
}

Laravel, how to call table name without hardcode by using same class model?

I suppose if you have to you can set a static variable on the model and use that to generate the table name:

class Something extends Model
{
protected $table = 'energydata_';

static $tableId = null;

public function getTable()
{
return $this->table . static::$tableId;
}

public static function tableId($tableId = null)
{
if (is_null($tableId)) {
return static::$tableId;
}

static::$tableId = $tableId;
}
}

Something::tableId('1001');

This is possible but may not be the best solution.



Related Topics



Leave a reply



Submit