0

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);

2 Answers 2

3

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.

1
  • I ended up creating one model per table.
    – smchae
    Jan 11, 2018 at 0:35
0

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';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.