Laravel Model attributes in camelCase. Two ways to have it.

Luís Nóbrega
3 min readSep 2, 2020

In this article, I will talk about how to have camelCase properties in Eloquent models. Let’s see these two ways.

Photo by Isabella Jusková on Unsplash

One of the issues in using models with Eloquent ORM is having the default behavior of all the attributes in snake_case.

Like this for example:

// We import the model class.
use App\Model\Image;
// Create a new instance.
$image = new Image();
// Use a property of the model.
echo $image->authorName;

Of course, this could be an issue, if we want to use a different convention.

And is this way, because, the attributes have the same names of the columns of the database.

But, if we want to use, for example, the camelCase convention, we need to make some changes in our models. Maybe camelCase because is more used as a coding style.

Let’s see what to change, in two different ways.

#1 — Use a Base Model

We can create a base model with getters and setters methods, who convert any access to camelCase properties, into snake_case format.

With this approach, we override the originals getAttribute and setAttribute from the Eloquent Model and convert any…

--

--

Luís Nóbrega

Web Developer at 25friday. Likes to travel, write and being a father.