codi05ro codi05ro - 1 year ago 38
MySQL Question

Get data for referenced object

I have a Recipe Model and FoodComponent Model which belongsTo Recipe.

RecipeModel :

class Recipe extends Model
protected $table = 'recipes';

protected $fillable = [

public function foods(){
return $this->hasMany('App\FoodComponent','id','food_id');

FoodComponent model:

class FoodComponent extends Model
protected $table = 'food_components';

protected $fillable = [ 'title',

public function recipes(){
return $this->belongsTo('App\Recipe','id','food_id');


public function index()
$recipes = Recipe::all();

return view('recipes.index')->with('recipes',$recipes);

And in the view I have

@foreach($recipes as $recipe)
{{ $recipe->foods }}

I get something like this :

[{"id":1,"menu_id":1,"title":"Pollo Locco","image":"images\/uploads\/foodcomponents\/99254.jpg","created_at":"2016-08-12 10:01:38","updated_at":"2016-08-12 10:01:38"}]

But I want just the 'title'.

I've tried with $recipe->foods->title. But is not working.

Can you give me an idea how can I display just the title please ?

Thank you !

Answer Source

Try this

@foreach($recipes as $recipe)
  @foreach($recipe->foods as $food)
   {{ $food->title }}