38

I am using laravel 5.2 ,i want to get all the column (attribute) name of selected eloquent model,is there way to do this?

following is my code in controller method

    if($request->method=="edit")
    {
        /*we are in edit mode details of given news ID should be attached*/
        $curNews=News::find($request->newsID);
        if($curNews==null)return back()->withErrors(["Unable to Edit News:No Data Found For Given News ID"]);

        foreach((array)$curNews->attributes as $key=>$val)
        {
            $data[$key]=$val;
        }

    }

    return view('adminarea.news.news-addedit',$data);
4
  • 1
    please display some code Commented Aug 22, 2017 at 12:52
  • to @aynber ,i just want column name as array Commented Aug 22, 2017 at 12:56
  • @joy it's basics of php, You already have object that has fieldName = 'some data', so it's not laravel question - it's all about basics of php (how to get attributes of object), sorry I'll downvote Your question Commented Aug 22, 2017 at 13:01
  • 1
    @num8er ,ya you are right but its platform to learn Commented Aug 22, 2017 at 13:02

3 Answers 3

88
$columns = Schema::getColumnListing('users'); // users table
dd($columns); // dump the result and die
Sign up to request clarification or add additional context in comments.

6 Comments

Import schema at the top - use Illuminate\Support\Facades\Schema;
This is how you get column names from table, not model - which was asked in question. If model tables are dynamic and may change - this is not good solution.
Does not work in 7.x
for some strange reason, it started auto-sorting keys in alphabetical order. \array_keys( $model->getAttributes() ) works for me
For newer Laravel versions (in my case 5.8) just use: use Schema; The path with Illuminate\Support\ etc. will not work.
|
22

If you want get the names of your attributes, you can try this

$item = News::find($request->newsID);

    $attributes = array_keys($item->getOriginal());
// or 
$attributes = array_keys($item->getAttributes());

2 Comments

if it is a collection use $items->first()->getAttributes()
This is a better way instead of using Schema.
2

don't know i am right or not, but i have overcome with following code,and its working for me.

    if($request->method=="edit")
    {
        /*we are in edit mode details of given news ID should be attached*/
        $curNews=News::find($request->newsID);
        if($curNews==null)return back()->withErrors(["Unable to Edit News:No Data Found For Given News ID"]);

        foreach($curNews->toArray() as $key=>$val)
        {
            $data[$key]=$val;
        }

    }

    return view('adminarea.news.news-addedit',$data);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.