How to return database table name in Laravel

Is there a way I can get the current database table used by the model I work in? I see that there is a table () function in Laravel / Database / Eloquent / model.php, but I was unsuccessful in calling it, calling it from the model I'm in.

+18
eloquent laravel
source share
7 answers

Edit April 2019: This answer is deprecated. See the new correct answer. Flynn San

Yes - Eloquent has a $table variable. There are two ways to access it:

 class yourModel extends Eloquent { public static $table = "differentTable"; function someFunction() { return yourModel::$table; } } 

or

 class yourModel extends Eloquent { public function someFunction() { return $this->table(); } } 

then in your code

 Route::get('/', function () { $model = new yourModel(); dd($model->someFunction()); }); 
+10
source share

Taylor has the answer to your question:

In the model class, you can do something like this:

 return with(new static)->getTable(); 

If you want all your models to be able to return the table name statically, then here is something like this:

 class BaseModel extends Eloquent { public static function getTableName() { return with(new static)->getTable(); } } class User extends BaseModel { } User::getTableName(); 
+42
source share

There is a public getTable () method defined in Eloquent \ Model so you can use $model->getTable() .

+40
source share

In my case, I am using laravel 5.4

return (new static)->getTable();

+5
source share

Since table is a protected property in the model class (Laravel> = 5), you will need an instance of your model.

Here is an example:

  DB::table( (new YourModelClassname)->getTable() ) ->update(['field' => false]); 
+2
source share

I just wanted to add the following for people from search engines:

If you don’t even want to instantiate a Model (faster?):

 $model = 'App\User'; $modelTable = str_replace('\\', '', Str::snake(Str::plural(class_basename($model)))); dd($modelTable); // will return "users" 

This may seem ugly, but that’s exactly how the getTable () method resolves this discreetly, so ...

You will need to use Illuminate\Support\Str; on top of your file.

Application: it is understood that you follow the framework standards (i.e.: the Post model has a posts table, the user model has a users table, etc.)

0
source share

In Laravel 4, use the static method

 $table_name = Model::getTable(); 

or " self " inside the Eloquent Model

 $table_name = self::getTable(); 
-2
source share

All Articles