How to Get Columns Names from Model in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hi,

This example is focused on how to get columns names from model in laravel. I would like to share with you laravel get column names from model. This tutorial will give you simple example of laravel get column names from query. I’m going to show you about laravel get all fields from model.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

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

So, let's see one by one example here.

Example 1:

You can see below controller code to getting columns names from model. let's see 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);

}

}

Output:

^ array:6 [â–¼

0 => "body"

1 => "created_at"

2 => "id"

3 => "slug"

4 => "title"

5 => "updated_at"

]

Example 2:

You can see below controller code to getting columns names from model method. let's see below 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);

}

}

Output:

^ array:6 [â–¼

0 => "body"

1 => "created_at"

2 => "id"

3 => "slug"

4 => "title"

5 => "updated_at"

]

I hope it can help you...

Tags :
Shares