smchae
smchae

Reputation: 1095

$this->setTable() does not work in Model

I am new to laravel. I want to change table name to given string in the constructor in model. The code below is what I tried, but it seems not working.

Any suggestion or advice would be appreciated.

Thank you

Model

class Custom extends Model
{
protected $guarded = ['id', 'ct'];

const UPDATED_AT = null;
const CREATED_AT = 'ct';

public function __construct(array $attributes = [], string $tableName = null) {

    parent::__construct($attributes);

    $this->setTable($tableName);
}

}

Controller

$tableName = 'some string';
$custom = new Custom([], $tableName);
$result = $custom->create($data);

Upvotes: 0

Views: 822

Answers (2)

sisve
sisve

Reputation: 19781

There is no Model::create method. This is magical shenanigans via Model::__call. Calling $custom->create(...) will forward the call to Builder::create which calls Builder::newModelInstance, which in turns calls Model::newInstance. This code does not know about the original model at all, it only knows about the $data attributes. (It is usually called in a static context, like Model::create(...), without an origin instance.)

The easiest workaround for you would be to create a new class deriving from Custom, and have it declare the $table property. This would require one model per table.

class Custom2 extends Custom {
    public $table = 'some string';
}

Upvotes: 0

Nuruzzaman Milon
Nuruzzaman Milon

Reputation: 312

You are only passing one parameter on the constructor function, but it expects 2 params. So, either pass two param, or make the constructor like this-

public function __construct($table = null, $attr = [])
{
    $this->setTable($table);
    parent::__construct($attributes);
}

But I don't understand why would you do that? The standard practice is create one model per table. You should do that either.

Upvotes: 3

Related Questions