Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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); 
like image 751
Jatin Parmar Avatar asked Aug 22 '17 12:08

Jatin Parmar


People also ask

How can I get column names in Laravel?

You can get the column name through a raw query. There are other ways too and we will discuss all. $query = “SHOW COLUMNS FROM $table_name”; $data['columns'] = \DB::select($query);

What does get () do in Laravel?

For creating ::where statements, you will use get() and first() methods. The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also, the find() method can be used with an array of primary keys, which will return a collection of matching records.

What is all () in Laravel?

all() is a static method on the Eloquent\Model. All it does is create a new query object and call get() on it. With all(), you cannot modify the query performed at all (except you can choose the columns to select by passing them as parameters). get() is a method on the Eloquent\Builder object.

How do I search in Laravel eloquent?

Searching Eloquent models Imagine you need to provide a search for users. Using Eloquent you can perform a search like this: User::query() ->where('name', 'LIKE', "%{$searchTerm}%") ->orWhere('email', 'LIKE', "%{$searchTerm}%") ->get();


2 Answers

$columns = Schema::getColumnListing('users'); // users table dd($columns); // dump the result and die 
like image 127
Kuldeep Mishra Avatar answered Oct 05 '22 13:10

Kuldeep Mishra


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()); 
like image 21
Pavel Avatar answered Oct 05 '22 11:10

Pavel