This example we will learn how to get all model columns name from Model Class in Laravel. I will guide you all with simple tip to get name of clomns in database from model. You can use this sample example to apply your project in some cases.
What's we need to do is to retreived all columns list from laravel eloquent model. We will use getColumnListing()
method to get the columns list. The two methods below will help you to understand more clearly.
Let's follow the examples below to help you retreived columns name:
We are going to call Schema method directly in controller method.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Article;
use Schema;
class ArticleController extends Controller
{
public function index()
{
$article = new Article;
$tb_name = $article ->getTable();
$columns = Schema::getColumnListing($tb_name );
dd($columns);
}
}
Your result may different which base on you table columns name.
^ array:7 [▼
0 => "title"
1 => "text"
2 => "slug"
3 => "id"
4 => "created_at"
5 => "updated_at"
6 => "status"
]
We are going to define a method in model class to return array of columns name.
<?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'
];
public function getColumns()
{
return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
}
}
Then we can call that method in controller file
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Article;
class ArticleController extends Controller
{
public function index()
{
$article = new Article;
$columns = $article->getTableColumns();
dd($columns);
}
}
^ array:7 [▼
0 => "title"
1 => "text"
2 => "slug"
3 => "id"
4 => "created_at"
5 => "updated_at"
6 => "status"
]
Hope these two example to get all column names in Laravel help you complete your task. Have a nice day!!
You might also like...
As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him