I found this concept is interesting, I learn and share things.
Here in this example, I append id_hash variable which then converted into method by this logic.
It takes first char and converts into upper case i.e. Id
and letter after underscore to uppercase i.e. Hash
.
Laravel itself add get and Attribute to combine all together it gives getIdHashAttribute()
class ProductDetail extends Model
{
protected $fillable = ['product_id','attributes','discount','stock','price','images'];
protected $appends = ['id_hash'];
public function productInfo()
{
return $this->hasOne('App\Product','id','product_id');
}
public function getIdHashAttribute(){
return Crypt::encrypt($this->product_id);
}
}
To simplify things append variable would be like this
protected $appends = ['id_hash','test_var'];
The method would be defined in the model like this
public function getTestVarAttribute(){
return "Hello world!";
}