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...
Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him