Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 621
notalentgeek Avatar asked Aug 23 '18 07:08

notalentgeek


1 Answers

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
like image 75
topher Avatar answered Sep 28 '22 06:09

topher