Search code examples
phplaraveleloquentlaravel-5.8eloquent-relationship

Laravel Eloquent appending a non-relation ship data with the result


I have this model file:-

    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Observation extends Model
    {
        protected $fillable = ['observation', 'recommendation', 'priority', 'report_asset_id'];
        protected $appends = ['facility'];
    
        public function attachments()
        {
            return $this->hasMany('App\ObservationAttachment');
        }
    
        public function report_facility()
        {
            return $this->belongsTo('App\ReportFacility');
        }
    
        public function getFacilityAttribute()
        {
            return $this->report_facility()->facility;
        }
  
}

And this is my query code:-

$observations = Observation::orderBy('created_at','desc')
       ->with('attachments')->get(); 

       return response()->json($observations);

I am trying to append getFacilityAttribute to be included in result array .

I tried to use the protected $append model array but got error :-

Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::facility()


Solution

  • The following line is incorrect:

    return $this->report_facility()->facility
    

    You are starting a query, calling the report_facility as a function (report_facility()), returns a query builder object, on which the facility function is unknown.

    You should do:

    return $this->report_facility->facility
    

    In this case, eloquent will give you the ReportFacility model, from which you can retrieve the facility property or relation.

    It's similar to:

    return $this->report_facility()->first()->facility