John Davidson

php - Eloquent relationship:: Attempt to read property "product_price" on null

0 comments
Message:


I'm trying to access a foreign key linked to my product table but I keep getting Attempt to read property "product_price" on null


here's my Order model


public function products()
{
return $this->hasMany(Product::class, 'id');
}

Product model


public function orders()
{
return $this->belongsTo(Order::class, 'product_id');
}

NewOrder Mailable


class NewOrder extends Mailable
{
use Queueable, SerializesModels;

protected $order;


public function __construct(Order $order)
{
$this->order = $order;
}


public function build()
{
return $this->markdown('emails.neworder', [
'customerName' => $this->order->customer_name,
'orderPrice' => $this->order->products->product_price,
]);
}
}

I want to be able to display the data in product table


Thanks



My Answer:
The issue is with how you are trying to access the product_price property in your NewOrder Mailable. Since products is a collection of products (hasMany relationship), you need to loop through each product to access its properties.

You can update your build method in the NewOrder Mailable like this:

php
public function build()
{
$orderPrice = 0;

foreach ($this->order->products as $product) {
$orderPrice += $product->product_price;
}

return $this->markdown('emails.neworder', [
'customerName' => $this->order->customer_name,
'orderPrice' => $orderPrice,
]);
}


This code will loop through each product in the order and calculate the total order price by summing up the product prices. This way, you can access the product_price property of each product in the order.

Rate this post

3 of 5 based on 4892 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us