Home » Php » php – How to dynamically set table name in Eloquent Model

php – How to dynamically set table name in Eloquent Model

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am new to Laravel. I am trying to use Eloquent Model to access data in DB.

I have tables that shares similarities such as table name.

So I want to use one Model to access several tables in DB like below but without luck.

Is there any way to set table name dynamically?

Any suggestion or advice would be appreciated. Thank you in advance.

Model:

class ProductLog extends Model
{

    public $timestamps = false;

    public function __construct($type = null) {

        parent::__construct();

        $this->setTable($type);
    }
}

Controller:

public function index($type, $id) {

    $productLog = new ProductLog($type);

    $contents = $productLog::all();

    return response($contents, 200);
}

Solution For those who suffer from same problem:

I was able to change table name by the way @Mahdi Younesi suggested.

And I was able to add where conditions by like below

$productLog = new ProductLog;
$productLog->setTable('LogEmail');

$logInstance = $productLog->where('origin_id', $carrier_id)
                          ->where('origin_type', 2);
How to&Answers:

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
}