In this post, i will let you know how to get table name from model in Laravel.
According to Laravel standard structure, We do not need to tell Eloquent which table will be used for model because by convention, model is used to interact with the table and plural name of model class will be used as table name.
So sometime you may need to get table name from model into your laravel application and you can easily get table name by using getTable()
method.
You will see there are lots of method available with Laravel Eloquent so using eloquent is best approach for your application.
Get Table Name From Model
- $product = new Product;
- $table = $product->getTable();
- print_r($table);
First i will define a method in model class by following way :
- <?php
- namespace App;
- use Illuminate\Database\Eloquent\Model;
- class Product extends Model
- {
- public function getTableColumns() {
- return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
- }
- }
Now you will get all columns of "products" table and if you need it in controller then you can get it by following way :
- $product=new Product;
- $columns=$product->getTableColumns();
- print_r($columns);