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

tangeu's avatar

Variable table name in eloquent model?

I am a beginner to laravel and the eloquent model (Last time I worked in PHP was PHP5.1) and have a potentially dumb/odd question.

The situation is: First of all I didn't design this database, nor can I change the design, but I do need to interface with it. Every month on the first of the month a bunch of new tables get created with "table_nameYYYYMM" (current year and month). The old PHP I know I'd make a string like "select * from table_name" . date('Ym') . " where" etc. and use it in a mysql_connect.

But what I want to know is if there is a way to do it in an eloquent model? Can I build a dynamic string and set it to the table name in a model? I've tried a few things that felt intuitive but I know my knowledge is way out of date so I wanted to check around and see if what I'm hoping to do is even possible before I waste a bunch of time.

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

Sure. Just write a method

public function getTable()
{
    return 'table_name'. now()->format('Ym');
} 
tangeu's avatar

@Sinnbeck Wait, is it really that easy? I guess I've got some reading to do, I really have to modernize my skills. This project was kind of dumped on me with a "You know this programming stuff don't you?" and it's been a while to say the least.

Thanks!

Please or to participate in this conversation.