Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 899
Chris G Avatar asked Dec 29 '12 14:12

Chris G


People also ask

How to get name from table in Laravel?

You can get table name simply call getTable() of model object, so how to call this method as bellow example. $item = new Item; $table = $item->getTable(); print_r($table);

How do I get column names in SQL laravel?

You can get all the column names from a table using the DB facade and Schema facade. You have to call the getColumnListing() method (using DB and Schema facade) by passing the table name as an argument to get all columns from the table.


2 Answers

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

like image 80
Flyn San Avatar answered Sep 22 '22 18:09

Flyn San


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(); 
like image 40
Lucky Soni Avatar answered Sep 20 '22 18:09

Lucky Soni