DEV Community

Abrar Ahmad
Abrar Ahmad

Posted on

3 1

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay