joelinman's avatar

Defining @property for a column name starting with a number in Eloquent Model

Came across this today at work in one of the models in one of our codebases - the previous developer had set the following:

@property ?string $4wd for a column called 4wd - why someone decided to use numbers at the start of column names in the first place has blown my mind, i've never come across it before.

It doesn't seem to have broken anything weirdly, but I am seeing a phpdocs error/warning because php variables cannot begin with a number.

Is this correct way to handle this with Eloquent?

I kind of think the variable should instead be something like $_4wd

0 likes
3 replies
LaryAI's avatar
Level 58

When dealing with column names that start with a number, you're right that PHP variables cannot start with a number. However, Eloquent can still work with these column names directly when interacting with the database. The issue arises when you want to document these columns using PHPDoc @property annotations, as PHPDoc follows the same variable naming rules as PHP.

To document a property that corresponds to a column starting with a number, you can use a variable name that starts with an underscore followed by the number, as you suggested. This won't affect Eloquent's functionality but will provide a valid PHPDoc annotation.

Here's how you can define the @property annotation for the 4wd column:

/**
 * @property ?string $_4wd Corresponds to database column '4wd'
 */
class YourModel extends Model
{
    // Model methods and properties
}

When accessing the 4wd column in your Eloquent model, you would still use the actual column name:

$model = YourModel::find($id);
$value = $model->{'4wd'}; // Accessing the '4wd' column

Remember that the @property annotation is for documentation purposes and does not affect how Eloquent accesses the database column. When you use the model attribute in your code, you should always refer to it with the actual column name, even if it starts with a number.

1 like
joelinman's avatar

I spent 15-20 minutes googling for this and Lary seems to have nailed it almost instantly!

Please or to participate in this conversation.