t0berius's avatar

load() with when() compared

Is there a more elegant way to use load() with some kind of when() condition?

I've tried the following:

    //only load physicalRelation when product is physical
    $product->when(!$product->is_virtual,function() use ($product){
        $product->load(['physicalRelation' => function($query){
            $query->orderBy('some_field', 'asc');
        }]);
    })->load([
        'relationX',
        'relationY', 
    ]);

This won't work, resulting in:

Call to undefined method Illuminate\Database\Eloquent\Builder::load()

I've ended up using:

   //load necessary relations
    $product->load([
        'relationX',
        'relationY',
    ]);

    //only load physicalRelation when product is physical
    $product->when(!$product->is_virtual,function() use ($product){
        $product->load(['physicalRelation' => function($query){
            $query->orderBy('some_field', 'asc');
        }]);
    });

Is there another way to make this maybe a bit more elegant?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The solution you provided is already quite elegant. However, if you're looking for an alternative approach, you can use the when() method in combination with the with() method to conditionally load the physicalRelation relation. Here's an example:

$product->load([
    'relationX',
    'relationY',
])->when(!$product->is_virtual, function ($query) {
    $query->with(['physicalRelation' => function ($query) {
        $query->orderBy('some_field', 'asc');
    }]);
});

This approach allows you to conditionally load the physicalRelation relation based on the value of $product->is_virtual. If it's true, the physicalRelation relation won't be loaded. Otherwise, it will be loaded with the specified ordering.

Note that the with() method is used instead of load() within the when() callback, as load() is not available on the query builder instance returned by when().

Please or to participate in this conversation.