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.
- Define a Trait:
app/Traits/CanGetTableNameStatically.php
<?php namespace App\Traits;
trait CanGetTableNameStatically
{
public static function tableName()
{
return with(new static)->getTable();
}
}
- Put in on your
Model
, or better yet, use aBaseModel
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;
// ...
}
- 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();
Author by
notalentgeek
Updated on June 19, 2022Comments
-
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 about 4 years
get_called_class()
is helpful if you want to definegetTableName()
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 almost 3 yearsthat is exaclty what he want to avoid, instantiating new model instance
-
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 over 2 yearswhy make this a trait when it's only used by base model?