Posts Learn Components Snippets Categories Tags Tools new About
/

How to Add Custom Attribute In Laravel Eloquent

Learn how to add custom attribute in Laravel Eloquent Model using the available append property the easy way

Created on Oct 17, 2021

116 views

In this short snippet, you will learn how to define the custom attributes in Laravel Eloquent Model using the "appends" property. For this example, we'll be using the "Post" model and we'll be adding a custom property called "cover".

Step 1: Define attributes in $appends Property


The first step is to define the "$appends" property and you can define it like below.
<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $appends = ['cover_url'];
}

Step 2: Define the accessor for that attributes


In the next step, you will have to define the accessor for the attribute. For this case let's say your existing data is stored in JSON, you can output the value like below.
public function getCoverUrlAttribute()
{
    return '/storage/' . $this->cover;
}

Step 3: Call the Attribute From The Front End


Now from anywhere within your code, you can call the attribute using the "cover_url" attribute.
<?php

$postCoverURL = Post::first()->cover_url; // 'storage/posts/first-post.jpg'

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components
)