Search code examples
laraveleloquentlaravel-5relationships

Laravel 5 / Eloquent: error when trying to get values from linked tables


I'm trying to create a simple Laravel 5 app for testing purposes. Everything seem to be set-up correctly (database, tables, etc.) and my model relationships are OK (tested with php artisan tinker). I still get an error "Undefined property..." and cannot understand how to get values from other linked tables within a view...

/resources/views/orders/index.blade.php

<ul>
@foreach( $orders as $order )
<li>Order # {{ $order->id }} - {{$order->status}} - {{$order->products->name}} - </li>
@endforeach
</ul>

=> Am I doing something wrong? How can I get the name of the product linked to the order?

OrdersController.php
public function index()
{
$orders = Order::all();
return view('orders.index', compact('orders'));
}

Here are my tables (migrations):

public function up()
{
Schema::create('orders', function(Blueprint $table)
{
$table->increments('id');
$table->timestamps();
$table->string('status');
});


Schema::create('products', function(Blueprint $table)
{
$table->increments('id');
$table->integer('order_id')->unsigned();
$table->timestamps();
$table->string('name');
$table->string('sn');
});

Here are my 2 models:

//File: App\Order.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model {

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

}

//File: App\Product.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model {

public function order()
{
return $this->belongsTo('App\Order');
}
}   

Thanks a lot for your help!


Solution

  • Issue here is that $order->products gives you collection of products not single product. You can use $order->products->first()->name or iterate over products to get names of each of the products.