Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Eloquent How to get property of model if column name contains a dash?

I have the following in my root route:

$user = User::all();
return $user->column-one;

Which returns the exception Use of undefined constant one - assumed 'one' even though I do have a column called column-one from my users table. So how do I get column-one from my model?

like image 672
camelCaseD Avatar asked Jan 04 '14 07:01

camelCaseD


People also ask

What does get () do in Laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function. Think of it like this: when you don't exactly know what a query will return then you need to use get() .

What is fillable property in Laravel?

The fillable property specifies which attributes should be mass-assignable. This can be set at the class or instance level. class User extends Eloquent { protected $fillable = array('first_name', 'last_name', 'email'); }

What is polymorphic relationship in Laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

How do I get column names in SQL Laravel?

How do I get column names in SQL laravel? You can get all the column names from a table using the DB facade and Schema facade. You have to call the getColumnListing() method (using DB and Schema facade) by passing the table name as an argument to get all columns from the table.


2 Answers

After digging through the source code for the eloquent model I found the magic method __get and learned that it was just a wrapper for the public function getAttribute which takes a string thus I'm now able to retrieve the column via $user->getAttribute('column-one');.

Edit:
See @Alexandre Butynski's comment below for a better solution than the one I used.

like image 149
camelCaseD Avatar answered Sep 28 '22 23:09

camelCaseD


I haven't tried this, but am curious if using camelCase for it would work. That's how it works for things like routes. For example: $user->columnOne.

I would however recommend renaming that column. That really doesn't map well in a PHP app.

Update - Try this:

$user->{"column-one"}

like image 20
LF. Avatar answered Sep 28 '22 23:09

LF.