skip to Main Content

I wonder if is there any method in Laravel that check if column_id is not null and contains a valid id, then bring the relation if It is ?

so for example:
instead of doing this:

if ($order->billing_address_id && $billingAddress = $order->billingAddresses){

how can I just type something like this:

$billingAddress = $order->getRelation('billingAddresses') // check the column_id first 
  • note:
    the original $order->billingAddresses runs the join sql without check the column_id if its null first

2

Answers


  1. It seems you’re misunderstanding the relation. Your $order->billing_address_id (a single integer column) can only point to a single relation. The orders table holds the reference to the billingAddress relation in this case.

    However, you are retrieving $order->billingAddresses (a hasMany relation) which means in order to know if there are any billingAddresses, you have to check the FOREIGN table billing_addresses since that (probably) holds a column named order_id.

    In the first case you can simply see in the order object itself if you should retrieve a billingAddress by checking the local key (Laravel automagically sees this and doesn’t run a query if local key = null). In the second case, you MUST check the foreign table so there will always run a query.

    Login or Signup to reply.
  2. $billingAddress = $order->when($order->billing_address_id, function (Builder $query) use ($order) {
        return $query->relationLoaded('billingAddresses') ? $order->billingAddresses : $query;
    });
    

    You can conditionally retrieve the relation if the column billing_address_id is not null and the relation NOT has already been loaded.

    P.S: it assumes relation defined b/w Order and BillingAddress models.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search