Search code examples
laravel-4modeleloquent

Update the table name at runtime not working - laravel Eloquent ORM


This is my model:

class Product extends \GlobalModel {
    protected $table = 'product';
}

I want to update the table name oops_product instead product at runtime.

I found getTable(); to get the table name from model and its working fine:

$tableName = with(new Product)->getTable();

But when i set the table name using setTable(); as per GitHub solution, its not updating the table name.

with(new Product)->setTable("oops_produdct");

Is there anything wrong?

Help will be appreciated.

edited:

$product = new Product(); 
$product->getTable(); // output: product 
$product->setTable("oops_product"); 
$product->getTable(); // output: oops_product 

now when i run this

$product->all(); 

it executes

"select * from product" 

instead of

"select * from oops_product"

Solution

  • all() is a static method that uses brand new instance and calls get() on it.

    So all you need is using proper method:

    $product = new Product;
    $product->getTable(); // products
    $product->setTable('oooops');
    $product->get(); // select * from oooops
    $product->first(); // select * from oooops limit 1
    etc...
    

    Just avoid using static Eloquent methods, since they obviously create new instance, that will have default table property.