laravel:how to get columns name of eloquent model? [duplicate]

徘徊边缘 提交于 2021-01-21 06:28:28

问题


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);

回答1:


$columns = Schema::getColumnListing('users'); // users table
dd($columns); // dump the result and die



回答2:


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());



回答3:


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);


来源:https://stackoverflow.com/questions/45818177/laravelhow-to-get-columns-name-of-eloquent-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!