Home / Snippets / How to Add Custom Attribute In Laravel Eloquent
How to Add Custom Attribute In Laravel Eloquent cover

How to Add Custom Attribute In Laravel Eloquent

11.9K

2 years ago

0 comments

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'
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this