Hello i am using the Eloquent many to many method to get values from 2 tables and show its values.
This is the Order model code:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Order extends Model
{
use HasFactory;
public $timestamps = true;
protected $fillable = [
'order_number',
'client',
'description',
];
public function clients()
{
return $this->belongsToMany(Client::class);
}
}
Here is the controller code to open a new window with all the values from table B
public function index()
{
$orders = Order::all();
return view('orders/index',compact('orders'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
Then this is what i am doin in the view:
@foreach($orders as $order)
{{$order->name}}
@endforeach
//this works
but if i do
@foreach($orders->clients as $client)
{{$client->name}}
@endforeach
//i get the error
Property [clients] does not exist on this collection instance.
Even though is declared in the model Order
2
Answers
can you try to include the model in the Order class as you have not defined it. Check below
Alternatively
both above would then make you able to reference the relationship.
All the best.
Your error is that you are assuming you are getting
clients
, that is true, but you are not getting them as a property like$orders->clients
,$orders
is aCollection
, that is whatBelongsToMany
returns.So, your code should be:
Due to each entry on a
Collection
is going to be anOrder
object, that is why$order->name
works ($order
is literally anOrder
).The only time
$orders->clients
is going to work for you, is when$order
is anOrder
:So, when you have a
Collection
in$orders
, there is no "property" (related to the relationship,clients
in this case), remember that aCollection
is anarray
with steroids, so theCollection
does not know anything about what it has inside of itself.