php - How to override result of hasMany relationship? -


imagine have couple of simple objects this:

<?php namespace app;  use illuminate\database\eloquent\model;  class user extends model {      public function posts()     {         return $this->hasmany("app\post");     } }  class post extends model {     public function user()     {         return $this->belongsto("app\user");     } } 

we'll \app\post object has database column called jsondata contains json-encoded data. when want display user's posts in view column decoded, need in controller:

$posts = auth::user()->posts()->get(); foreach ($posts $post) {     $post->jsondata = json_decode($post->jsondata); } return view("user.show", ["posts"=>$posts]); 

is there way avoid foreach loop in controller , json decoding @ lower level?

i'm sure in app\user::posts() doesn't other places need display decoded data. tried defining app\post::get() override parent method, doesn't work because hasmany() doesn't seem return instance of model @ all.

it can done in different places/ways, suggest use append property in model if want data decoded everywhere , every time retrieve post model, or mutator.

see https://laravel.com/docs/master/eloquent-mutators

in model can define:

protected $appends = [     'name_of_property' ];  // calculated / mutated field public function getnameofpropertyattribute() {     return jsondecode($this->jsondata); } 

you can access property with:

$post->name_of_property

note conversion camelcase snake_case , conversion getnameofpropertyattribute > name_of_property. default need respect convention working automagically.

you can substitute name_of_property , nameofproperty want accordingly.

cheers