Home Laravel How to Get Columns Names from Model in Laravel?

How to Get Columns Names from Model in Laravel?

by Shahriar Sagor
Get Columns Names from Model

Today now in this example i will be focused on how to Get Columns Names from Model in laravel application. Here i would like to share with you an example of laravel get column names from model. So in this tutorial i will give you a very simple example of laravel how to get column names from query. Here I’m going to show you about laravel get all the fields from model.

We can also use this example with laravel 6, laravel 7, laravel 8 and laravel 9 any versions.

Sometimes, we have to get all the columns list from laravel eloquent model. So there are a few ways to get the all fields list of table in laravel application. Here i will use the getColumnListing() method of laravel schema. Also here I will give you two examples of getting columns name from a model.

So, let’s start and see one by one example here.

Example 1:

We can see in below controller code to getting columns names from model. let’s see the below example code:

Controller Code:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
use Schema;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $post = new Post;
        $tableName = $post->getTable();
  
        $columns = Schema::getColumnListing($tableName);
  
        dd($columns);
    }
}

Example 2:

We can also use the below controller code to getting the columns names from model method. let’s see below the example code:

Post.php Model Code:

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Post extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'title', 'body', 'status'
    ];
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function getTableColumns() {
        return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
    }
}

Controller Code:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $post = new Post;
  
        $columns = $post->getTableColumns();
  
        dd($columns);
    }
}

Read Also: How to Send Automatic Email in Laravel 9?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like