laravel:how to get columns name of eloquent model?

Stefan Izdrail

Founder & Senior Architect · 2026-06-29

Laravel Company
Title: Effortlessly Retrieve Column Names of Eloquent Models in Laravel 5.2 Introduction: In the world of Laravel, working with eloquent models is a common practice for interacting with database data. Sometimes, you might need to access all the column names or attributes of a specific model instance. This blog post will guide you through different approaches to get columns names in Laravel 5.2 and showcase practical examples. 1. Using Array Access: To retrieve column names via array access, follow these steps: - Firstly, fetch the eloquent model with your desired ID using find(). This ensures we're working on a valid instance. - Iterate through the attributes of the current model, which is an associative array, where each key represents a column name and the value corresponds to its data. - Create a data array containing all the keys from the given model. You can then use this in your view as required: $data = []; // Initialize empty data array foreach ((array) $curNews->attributes as $key => $val) { $data[$key] = $val; } 2. Using Laravel Collections: Collections are PHP objects that provide a convenient way to iterate and manipulate data. In this approach, you can call the keys() function on your Eloquent model instance and pass it into your view. This returns all column names as an array: $model_keys = collect($curNews)->keys(); // Create collection of all keys for current model return view('adminarea.news.news-addedit', ['model_keys' => $model_keys]); 3. Using Laravel Collections with Custom Callbacks: In cases where you require only specific columns, you can use the map function along with a custom closure to obtain an array of column names. This may be useful for displaying relevant fields in different contexts. Here's how it works: $model_keys = $curNews->get()->map(function ($key) { return $key; // Map each key to a new array containing column names }); 4. Using Laravel's Collection Methods for Flexible Solutions: Laravel's Collections offer multiple ways of getting the necessary data based on your requirements. By leveraging these methods, you can easily create custom functions to extract column names and other useful information from your models in a reusable manner: $model_keys = $curNews->get()->pluck('column1', 'column2', 'column3'); // Extract specific columns using pluck() Conclusion: Retrieving column names of Eloquent models is essential in various use cases, such as displaying model data or validating input fields. In Laravel 5.2, there are multiple ways to achieve this goal. While the code examples provided demonstrate several methods, it's crucial to choose the most suitable approach based on your particular application requirements. By leveraging Laravel's powerful tools and best practices, you can ensure efficient data handling and scalable solutions.