Laravel 5: “Trying to get property of non-object”

2019-09-17 09:26发布

问题:

I'm trying to create a simple Laravel 5 app for testing purposes and I'm still struggling with displaying the desired data through models relationships. Everything works fine when I test models relationships through artisan tinker. In my index view, everything is fine... until I use a second linked model, which gives me the error in the subject.

Here are my tables (migrations):

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');
});

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

Here are my 3 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');
    }

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

//File: App\Product.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model {

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

//File: App\Service.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Service extends Model {

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

//My simple controller OrdersController.php

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

And finally my view "/resources/views/orders/index.blade.php"

<ul>
    @foreach( $orders as $order )
        <li>
            Order# {{ $order->id }} -             //this line is OK
            {{$order->products->first()->name}} - //this line is OK 
            {{$order->services->first()->name}} - //as soon as I add this line, I get the error! 
        </li>
    @endforeach
</ul>

=> Am I doing something wrong? Isn't it possible to retrieve data from 2 "external" models within the same view? Thanks a lot for your help!

回答1:

Does every order have at least one service assigned? My guess is not, in which case you should wrap it in an if statement:

@foreach( $dossiers as $dossier )
    <li>
    Order# {{ $order->id }}
    @if($product = $order->products->first())
        {{ $product->name }}
    @endif
    @if($service = $order->services->first())
        {{ $service->name }}
    @endif
    </li>
@endforeach