Get the Table Name From a Model in Laravel

RMAG news

Sometimes we need to reference table names throughout our codebase, like when we’re using the DB facade.

Although table names don’t change often, I still get an uneasy feeling of hardcoding them. It’s so much better to reference the model directly so we have one source of truth for the table name.

So, let’s learn how to do that! We’ll also create a trait that allows static access to any of our model table names to keep our code a little tidier.

If you don’t know, Laravel provide a method to get table name from model instance

((new User))->getTable()

Above code should return the table name, in our case its users.

But we don’t have new instances always. Its better if we can get the table name statically.
We can get the table name by following.

Add method in model

public static function getTableName()
{
return with(new static)->getTable();
}

Get the table name statically

User::getTable() // users

Tip

You can put method in trait and drop it any mode.

Leave a Reply

Your email address will not be published. Required fields are marked *