I have an Order, Product and OrderProduct model. The Order has a belongsToMany relationship with Products as in
public function products(){
return $this->belongsToMany('App\Product')->withPivot('group');
}
So a user creates an order into the database:
$order = Order::create([
'order_id' => $payment->metadata->order_id,
'user_email' => $request ->email,
]);
and we also save the products (note they have the same order_id as Order):
foreach (Cart::content() as $item){
OrderProduct::create([
'order_id' => $payment->metadata->order_id,
'product_id' =>$item->model->id,
'group' => $item->options->group,
]);
}
So then I want to send an e-mail with the Order information and the Products information retrieved from the DB, this is in my webhook file and when the payment is paid, an email is sent:
//Let's send an email.
$order = Order::where('order_id', '=', $payment->metadata->order_id)->firstOrFail();
Mail::send (new OrderPlaced ($order));
The email shows all the order information like order_id and user_email in my view through the output {{$order->order_id}} and {{$order->user_email}} but I don't see the products when I try to loop through them with:
@foreach ($order->products as $product) {{$product->name}} @endforeach
It just returns nothing, no error, nothing. A dd ($product) returns nothing. What am I overlooking here?
My thoughts:
1. I am not using id as a primary key, so maybe I need to specify second and third arguments in the belongsToMany relationship?
2. The $order variable defined prior to Mail, maybe I can't get the relationship through here?
So I figured this out, maybe others will at some time face the same problem: My foreign keys were not set right in the migration. So fixing the foreign keys and then doing a php artisan migrate refresh solved it.