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
Mysql: Get Total in Last Row of MySQL Result
How to Get the Columns Names Along with Resultset in PHP/Mysql
How to Start a Windows Gui Program Using PHP
How to Convert Special Characters to Normal Characters
Convert Hex Code into Readable String in PHP
JavaScript or Jquery Doesn't Work in Dynamically Generated Content
How to Subtract 24 Hour from Date Time Object in PHP
Is It Acceptable to Use a Mix of Object Oriented Style with Procedural Style in Coding PHP
Check If Username Exists in MySQL Table via PHP
Does the Use Keyword in PHP Closures Pass by Reference
In Laravel 5, How to Disable Verifycsrftoken Middleware for Specific Route
Set Quantity Minimum, Maximum and Step at Product Level in Woocommerce