I'm developing a project with complex model's relations (Laravel)
I have more than 10 tables with many foreign keys.
Now, I'm stuck to handle error when access a deep property through many levels of eloquent objects. Below is example of relations
Category
||
||
Product === Seller === User === Country === Region
|| || ||
|| || ||
Cart Seller Level Buyer
|| ||
|| ||
Invoice ==============================
Here is a simple script to get country of seller/buyer from specified invoice - Eloquent
$invoice = Invoice::find($id);
$countrySeller = $invoice->cart->product->seller->user->country; //6 levels
$countryBuyer = $invoice->buyer->user->country; // 4 levels
In a bad luck day, the script got error Trying to get property of non-object in laravel.log - without line of error.
After debug, I found problem. Missing data on accessing property.
First solution looks crary. It is checking is set for all child properties
if (isset($invoice->buyer) && isset($invoice->buyer->user) && isset($invoice->buyer->user->country)) {
// Do sth
}
I tried to wrap above script into try-catch block. It was also not be worked.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire