Search code examples
phplaraveldingo-api

Laravel Dingo get data from multiple tables


I'm trying to retrieve data from two tables with relationship one-to-many. I need it to return in one response since it will be displayed simultaneously. However, I don't understand how to return extended object. For now I have something like this in controller

public function show(Site $id)
    {
        foreach ($id->features() as $feature) {
            $id->features[] = $feature;
        }

        return $id;
    }

And this is my model

class Site extends Model
{
    protected $fillable = ['path', 'site_link'];

    public $timestamps = false;

    public function features() {
        return $this->hasMany('App\SiteFeature');
    }
}

For now it returns an empty array of features property.


Solution

  • If you are using implicit model binding then Lazy eager Load features relationship in controller action because model is already loaded

    public function show(Site $site)
    {
        $site->load('features');
    
        return $site;
    }
    

    If no implicit model binding then Eager load features using with at time of model loading

    public function show($id)
    {
        $site = Site::with('features')->find($id);
    
        return $site;
    }
    

    Check details for loading relationship https://laravel.com/docs/5.6/eloquent-relationships#constraining-eager-loads