Home > Tips & Tricks > Add Custom Columns to Laravel Models Using Accessors

Add Custom Columns to Laravel Models Using Accessors

Do you know what is Accessors and how to use them to add custom columns to laravel models? Let’s see in this tricks.

What is Accessors in Laravel?

The Accessors in laravel are custom methods defined by the user. You have to create a custom method in Models. Accessors are used to format the columns/attributes when you are fetching from the database.

Using Accessors in Laravel

By using this, we can combine the multiple table columns in one attribute or any kind of customization with data like uppercase, lowercase, string search/replace, etc. And you can use it as a property.

Let’s see the following code.

In the above example, we made an Accessors function to get the full name of the user by combining the two columns’ firstname and lastname.

After making the Accessors in laravel models, you can use it as the following code.

Hope you like the information!

Being Tricky 😉

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment