DEV Community

Abrar Ahmad
Abrar Ahmad

Posted on

Get the Table Name From a Model in Laravel

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()
Enter fullscreen mode Exit fullscreen mode

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.

  1. Add method in model
public static function getTableName() 
{
    return with(new static)->getTable();
}
Enter fullscreen mode Exit fullscreen mode
  1. Get the table name statically
User::getTable() // users
Enter fullscreen mode Exit fullscreen mode

Tip

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

Top comments (0)