use relationship in model accessor in laravel
laravel, laravel-5.4, php
Solution
Yikes some interesting answers here.
FYI to those coming after me- `getFooAttribute()` should return the data, and not modify the internal attributes array.
If you set a new value in the attributes array (that doesnt exist in this model's db schema) and then attempt to save the model, you'll hit a query exception.
It's worth reading up the laravel docs on attribute accessors/mutators for more info.
Furthermore, if you need to access a related object from within the model (like in an accessor) you ought to call `$related = $this->getRelation('foo');` - note that if the relation isnt loaded (e.g., if you didnt fetch this object/collection with eager loaded relations) then `$this->getRelation()` could return null, but crucially if it is loaded, it won't run the same query(ies) to fetch the data again. So couple that with `if (!$this->relationLoaded('foo')) { $this->loadRelation('foo'); }`. You can then interact with the related object/collection as normal.
Problem
Suppose I have a `Course` model like this : ``` class Course extends Model { public $primaryKey = 'course_id'; protected $appends = ['teacher_name']; public function getTeacherNameAttribute () { $this->attributes['teacher_name'] = $this->teacher()->first()->full_name; } public function teacher () { return $this->belongsTo('App\User', 'teacher', 'user_id'); } } ``` And in the other hand there is a `User` model like this : ``` class User extends Authenticatable { public $primaryKey = 'user_id'; protected $appends = ['full_name']; public function getFullNameAttribute () { return $this->name . ' ' . $this->family; } public function course () { return $this->hasMany('App\Course', 'teacher', 'user_id'); } } ``` As you can see there is a `hasMany` relationship between those. There is an `full_name` accessor in User model. Now I want to add a `teacher_name` accessor to `Course` model that uses it's `teacher` relations and gets `full_name` of teacher and appends to `Course` always. In fact I want whenever call a `Course` model, it's related teacher name included like other properties. But every time , when call a Course model , I got this error : ``` exception 'ErrorException' with message 'Trying to get property of non-object' in D:\wamp\www\lms-api\app\Course.php:166 ``` That refers to this line of Course model : ``` $this->attributes['teacher_name'] = $this->teacher()->first()->full_name; ``` I do not know how can I solve that and what is problem exactly.