Reputation: 592
I am trying to build an API with laravel, i have a shop, comment, user, food and shop_food table. i want the api to show a list of shops, each with shop information, 5 foods, comments on shop and user who gave comments.
<?php
namespace App;
use App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'shops';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name','description','address','district','city','country','lat','long','speciality'];
/**
* Get the shop associated with the location.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
/**
* Get the shop associated with shops.
*/
public function foods()
{
return $this->belongsToMany('Food', 'shop_food',
'shop_id', 'food_id');
}
}
My shop controller
<?php
namespace App\Http\Controllers;
use App\Shop;
use App\Comment;
use Illuminate\Http\Request;
class ShopController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$shops = Shop::with('comments.user')->get();
return response(['shops' => $shops->toArray(), 'error'=>'false'], 200);
}
what do i need to do please help. Right now cos of the errors i am only able to display shop->comments->user but i need to add food to the api
Upvotes: 0
Views: 1753
Reputation: 846
If the relation between Shops and Foods are available in methods... You can do something like this:
$shops = Shop::with('comments.user', 'foods')->get();
This way you get multiple relationships and when you $shop->toArray() it will show in your API... Right?
Upvotes: 1