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'
Leave a reply