Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aurorame's avatar

Model::setTable() cannot be called statically

How to call setTable in query like this Model::setTable('table_2')->where('id', 1)->first();?

0 likes
9 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Why do you need need to change the table at runtime? Maybe there is a better way if you can explain what you are trying to do

(new Model)->setTable('table_2')->where('id', 1)->first(); 
1 like
aurorame's avatar

@Sinnbeck I have project that use 3 more databases on different locations. All database structure is the same, but one database has another table names. I think about this:

if ($request->var == ..) {
   use default table
} else {
   use not-default table
}
Sinnbeck's avatar

@aurorame ok that sounds like it's going to be hard to maintain. If it isn't determined at the start of the request, I'm not sure I have a good solution. I was thinking of adding the getTable() method to the model and have the logic there

But did my solution work?

Sinnbeck's avatar

@aurorame ok great. You can try playing around with the getTable() method on the model, but I don't know if it is a good fit

aurorame's avatar

@Sinnbeck getTable() return used table name, not set table, don't understand how i can use it in my solution :/

Sinnbeck's avatar

@aurorame if it is some overarching logic for what table to use, you can let the model decide. On the model

public function getTable()
{
    return request()->input('foo') == 2 ? 'table_1' : 'table_2';
}

This is automatically called by laravel on all database queries

1 like
aurorame's avatar

@Sinnbeck I have to put this in a model where I need this logic and call in query like Model::getTable()->..., right?

Please or to participate in this conversation.