Collection:::Orders does not exist - Laravel

Asked

Viewed 45 times

0

starting this topic by saying that I’m new to Laravel, but come on, I’m having a problem with Collection, is giving an error saying that it does not exist and that I made this connection in the Model as shown below.

Order Controller

public function index()
{
    
    $customer = Customer::all();
    $orders = $customer->orders()->get();

    return view('admin.orders.index', compact('orders'));
}

Customer Model

public function orders()
{
    return $this->hasMany(Order::class);
}

Order Model

public function customer()
{
    return $this->belongsTo(Customer::class);
}

1 answer

1

This error happens because you are trying to execute the method of Model in a Collection, the method all() returns a collection (which can be understood as an array) of Models. To load the relations by the collection use the method load(), in accordance with documentation:

$customers = Customer::all();
$customers->load('orders');
// obter orders do primeiro customer:
$orders = $customers[0]->orders

How you used $customer in the singular think possible that the problem is that you want to get only one record, for that the code should be something like this:

$customer = Customer::find($id); // retorna só um Model
$orders = $customer->orders; // faz a mesma coisa que $customer->orders()->get()
  • So Pedro, I’m trying to bring the information of the Orders, that together with him has a customer, in the way you showed, he only brings information of the customers and no information of the order. It would be better if I bring the order information and then pull the customer?

  • I ended up doing it backwards and it worked, $Orders = $this->order->paginate(10); $Orders = $Orders->load('Customer');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.