How to get table name and table column names from model in Laravel 5?

How to get table name and table column names from model in Laravel 5?

In this post we will give you information about How to get table name and table column names from model in Laravel 5?. Hear we will give you detail about How to get table name and table column names from model in Laravel 5?And how to use it also give you demo for it if it is necessary.

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

  1. $product=new Product;
  2. $table=$product->getTable();
  3. print_r($table);
$product = new Product;
$table = $product->getTable();
print_r($table);


Get Table Column Name From Model

First i will define a method in model class by following way :

  1. <?php
  2. namespace App;
  3. use IlluminateDatabaseEloquentModel;
  4. class Product extends Model
  5. {
  6. public functiongetTableColumns(){
  7. return$this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
  8. }
  9. }
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
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 :

  1. $product=new Product;
  2. $columns=$product->getTableColumns();
  3. print_r($columns);
 $product=new Product;
 $columns=$product->getTableColumns();
 print_r($columns);

If you face any problem then please feel free to comment below.

Label :

PHP

How to draw shapes in PHP

Laravel PHP Framework

How To

Web Development

Hope this code and post will helped you for implement How to get table name and table column names from model in Laravel 5?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  6  =  7

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US