Below is the code for model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $appends = [
"desc"
];
protected $fillable = ['id'];
public function getDescAttribute()
{
return strip_tags( $this->attributes['description'] );
}
}
So now when i do
$product = Product::first();
It doesn't return desc field in the $product, though when i do $product->desc it returns the result, but i want that result to be appended in the model itself.
The following code gives me error
$product = Product::first()->get(['desc']);
It runs
Select desc from products...
But as the desc is not there i am getting error.
Is anything I'm doing wrong?
Fields that you add to $appends array are only appended when object is serialized to array/JSON. Otherwise it doesn't make sense to define this attribute until it's really needed - that's why you're getting the value when you access $product->desc. It's done to save unnecessary operations - calculating the value of a custom attribute could involve some heavy operations and is delayed till it's really needed.