How can I get table name, statically from Eloquent model?

10,642

Solution 1

You can add to your model.

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

Then you can get table name with Something::getTableName()

Solution 2

Here's a slight modification 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 with(new static)->getTable();
    }
}
  1. Put in on your Model, or better yet, use a BaseModel and all your other models extends it.

app/Models/BaseModel.php

<?php namespace App\Models;

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

class BaseModel extends Model
{
    use CanGetTableNameStatically;

    // ...
}
  1. On your other models, you can set the custom table name on Laravel's reserved attribute: protected $table

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

Solution 3

Not static but elegant approach

with(new Something)->getTable();
Share:
10,642
notalentgeek
Author by

notalentgeek

Updated on June 19, 2022

Comments

  • notalentgeek
    notalentgeek almost 2 years

    Right now I have this code to check to which table an Eloquent model is connected into.

    $s = new Something();
    dd($s->getTable());
    

    Is there anyway I can get the table without instantiating new Something object?

    I was thinking something like these codes:

    Something::getTable();
    

    But there will be ..should not be called statically error.

  • Ryan
    Ryan about 4 years
    get_called_class() is helpful if you want to define getTableName() in a parent model that the actual models extend. stackoverflow.com/a/283094/470749
  • М.Б.
    М.Б. about 3 years
    @Ryan Or return (new static)->getTable() in base model.
  • fudo
    fudo almost 3 years
    that is exaclty what he want to avoid, instantiating new model instance
  • Abdul Rehman
    Abdul Rehman over 2 years
    +1 This is the exact solution I came up with myself when I was looking for the answer and use as needed.
  • user34345352
    user34345352 over 2 years
    why make this a trait when it's only used by base model?