I have a very simple tables association with laravel 4 :
foods table
id
name
food_category_id
food_categories table
id
name
Here are my two models:
//models/Food.php
class Food extends Eloquent {
public function food_category()
{
return $this->belongsTo('FoodCategory');
}
}
//models/FoodCategory.php
class FoodCategory extends Eloquent {
}
When trying to extract category information form the Food model :
in controller:
class FoodController extends \BaseController {
public function index()
{
$foods = Food::all();
return View::make('admin/food/index',compact('foods'));
}
}
In view:
@foreach($foods as $food)
<tr>
<td>{{ $food->id }} </td>
<td>{{ $food->name }}</td>
<td>{{ $food->description}}</td>
<td>{{ $food->price}}</td>
<td>{{ $food->food_category->name }}</td>
</tr>
@endforeach
I get the below error message :
Trying to get property of non-object (View: /Library/WebServer/Documents/xxx/test/app/views/admin/food/index.blade.php)
Based on the dynamic properties, data should be available from ->food>category
Debugging with dd(DB::getQueryLog()) :
array(2) { [0]=> array(3) { ["query"]=> string(44) "select * from `users` where `id` = ? limit 1" ["bindings"]=> array(1) { [0]=> int(6) } ["time"]=> float(0.79) } [1]=> array(3) { ["query"]=> string(21) "select * from `foods`" ["bindings"]=> array(0) { } ["time"]=> float(0.32) } }
======= UPDADED
When adding eager loading :
$foods = Food::with('food_category')->get();
I got :
array(3) { [0]=> array(3) { ["query"]=> string(44) "select * from `users` where `id` = ? limit 1" ["bindings"]=> array(1) { [0]=> int(6) } ["time"]=> float(0.52) } [1]=> array(3) { ["query"]=> string(21) "select * from `foods`" ["bindings"]=> array(0) { } ["time"]=> float(0.42) } [2]=> array(3) { ["query"]=> string(67) "select * from `food_categories` where `food_categories`.`id` in (?)" ["bindings"]=> array(1) { [0]=> string(1) "1" } ["time"]=> float(3.23) } }
Try with eager loading:
$foods = Food::with('FoodCategory')->get();