0

i would like to display latest order status name from database but i have a problem with displaying data. Here is my code:

OrderController

    class OrderController extends Controller
    {
        public function index()
        {
            $orders = Order::with('shippingAddress', 'billingAddress', 'carrier', 'payment', 'status')->limit(300)->orderBy('id', 'DESC')->get();

        }
}

OrderModel (cutted)

public function status()
    {
        return $this->hasMany('App\Ss\Models\OrderHistory','id_order', 'id')
            ->orderBy('date_add', 'DESC')
            ->limit(1)
            ->with('statusLanguage');
    }

OrderHistory model

class OrderHistory extends Model
{
    protected $table="order_history";
    public $timestamps = false;

    public function statusLanguage(){
        return $this->hasOne('App\Ss\Models\StatusLanguage', 'id_status', 'id_status');
    }
}

How i tried to display:

{{ $order->status()->statusLanguage()->name ?? 'No status' }}
{{ $order->status()->statusLanguage->name ?? 'No status' }}
{{ $order->status->statusLanguage->name ?? 'No status' }}

Each time result was error like "Property [statusLanguage] does not exist on this collection instance." or similar.

When i try to dd($order->status) it show returned relation with data what i needed: enter image description here

So where is mistake?

Marek Kaliszuk
  • 577
  • 5
  • 21

2 Answers2

1

You are trying to get the statusLanguage from a collection of OrderHistory instances instead of from a single instance. Try $order->status[0]->statusLanguage->name.

D Malan
  • 10,272
  • 3
  • 25
  • 50
  • Yes, You are right! When i tried to foreach (@cheran suggestion) it showed some json data: {"id":28698,"id_order":11003,"id_status":18,"id_employee":0,"date_add":"2019-02-12 21:13:23","status_language":{"id_status":18,"id_lang":3,"name":"PayU"}} I thought that i can display text directly (because i should be one row/one column always) – Marek Kaliszuk Feb 25 '19 at 12:15
  • @MarekKaliszuk If you only want one row, you should maybe alter your code, because you created a relationship where multiple results are possible. – Douwe de Haan Feb 25 '19 at 12:27
1

You're trying to acces a Collection of models as a single object.

You could do the following in your blade file:

@foreach($order->status as $status)
    {{ $status->statusLanguage->name ?? 'No status' }}
@endforeach

More information about relationships with eloquent here.

Douwe de Haan
  • 6,247
  • 1
  • 30
  • 45