'How to return database table name in Laravel

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



Solution 1:[1]

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

Solution 2:[2]

Taylor has an answer to your question:

Within the model class you can do something like this:

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

If you want all your models to have the ability to return table name statically, then so something like this:

class BaseModel extends Eloquent {

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

}

class User extends BaseModel {

}


User::getTableName();

Solution 3:[3]

Edit April 2019: This answer is now out of date. See the new correct answer by Flyn San

Yes - Eloquent has a $table variable. There are two ways you can access this:

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());
});

Solution 4:[4]

In my case, i'm using laravel 5.4

return (new static)->getTable();

Solution 5:[5]

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

Here is a case example:

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

Solution 6:[6]

You can get name of a model's table by following code:

If we have a Model as ModelName:

ModelName::query()->getQuery()->from

This method also works fine in case of custom table name that are defined by protected $table = 'custom_table_name' in the Model.

Solution 7:[7]

Based on Lucky Soni answer, there is another easy trick if you want to directly call it from Vontroller or View.

Tested in Laravel 6, and I keep using it, if you are "One Line Programmer" who hates extra line instance declaration. No need for extra lines in Model file too.

$string_table_name = with(new \App\Model\TableModelName)->getTable();

or better you may also be able to just call this

$string_table_name = (new \App\Model\TableModelName)->getTable();

It will return plain string of the tabel name even if you rename $table variable inside model class.

EDIT :

Minus Rep ?? Maybe you should try this first in your controller instead making new function in model class just to get table name and no need to declare the object when calling.

with() itself is Laravel helper function that returns an object of the class. and inside class that extends Model, already has function getTable(). So, you don't have to put another new redundant function inside model class. It seems the latest version, you can just call (new Class) without with() function.

The difference between this answer and Lucky's answer, mine doesn't make any new function inside Model class to get the table name, even you can just call the function inside the Controller and View without declaring the object of model class. It's for beautify the code.

While Lucky's answer create new function that inside Model class, and you need to call the function from the object.

Solution 8:[8]

It will return the table name from the model. perfectly worked on laravel 8

app(Modelname::class)->getTable()

you have to replace Modelname with your model class

Solution 9:[9]

Simple way to get table name from Laravel Model by this:

$tableName = app(\App\User::class)->getTable();

Don't forget to replace:

\App\User

With Model path.

Solution 10:[10]

Based on tailor Otwell's answer you could use something like this:

with(new Model)->getTable();

Note: tested on versions 5.x, 6.x, 7.x, 8.x and it works well.

Solution 11:[11]

another solution is to use the resolve helper like so:

resolve('\\App\\Models\\User')->getTable()

Solution 12:[12]

Here's an other approach so that you can get a model's table name statically.

  1. Define a Trait: app/Traits/CanGetTableNameStatically.php
<?php namespace App\Traits;

trait CanGetTableNameStatically
{
    public static function tableName()
    {
        return (new static)->getTable();
    }
}
  1. Extend your required Model or BaseModel with the use statement.

app/Models/BaseModel.php

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Traits\CanGetTableNameStatically;

class BaseModel extends Model
{
    use CanGetTableNameStatically;

    // ...
}

On your models, if you set the custom table name on Laravel's reserved attribute: protected $table then it will still work & return correct table name.

app/Models/Customer.php

<?php namespace App\Models\Master;

use App\Models\BaseModel;

class Customer extends BaseModel
{
    protected $table = 'my_customers';

    // ...
}

Usage: just call YourModel::tableName() anywhere.

In Views:

{{ \App\Models\Customer::tableName() }}

When doing Joins:

DB::table( Product::tableName() . ' AS p' )
->leftJoin( ProductCategory::tableName() . ' AS pc', 'pc.id', '=', 'p.category_id')
// ... etc

Note: I use this approach where needed but full disclosure, I found another answer here that have the exact same approach, so I copy pasted here for reference of course with citation thanks to @topher

Solution 13:[13]

None of the answers so far will get you the table name with the prefix, if you are using a table name prefix. At this time it seems like we need to concatenate the prefix with the table name ourselves if we want the real name of database table.

Here's how to get the table name including the table prefix:

echo \App\MyModel::query()->getQuery()->getGrammar()->getTablePrefix() . app(\App\MyModel::class)->getTable();

Solution 14:[14]

in laravel 7.x (i'm used) you can get table name with (new Target())->getTable();

$query->where('parent_id', function ($query) use ($request) {
    $query->select('id')->from((new Target())->getTable())->where('unit_id', $request->unit_id);
});

hope it's helps

Solution 15:[15]

To people who want to get table name from a Builder object instead of other object, here you are:

$conn = DB::connection("my_private_mysql_conn");
$my_builder_object = $conn->table("my_table_name");

//This will print out the table name
print $my_builder_object->from;