Just Developer Just Developer - 2 months ago 8
PHP Question

Laravel relationship through a parent

I created a model for services that are packed with modules and each modules has a price. Multiple modules create the price for that service.

- Service #1
-- Module 1 ($20)
-- Module 2 ($40)


class Services extends Model
public function modules()
return $this->belongsToMany('App\Services\Modules');

each module links to a price

class Modules extends Model
public function price()
return $this->hasOne('App\Services\Pricing', 'product')->where('type', 'module');

and a
table that links services to modules. The problem is what kind of relationship should I create to be able to
the module prices for each service because I created an ugly patch with loops and burning 15 more queries per request

$prices = [];
foreach ($services->modules as $modules )
$prices[] = $modules ->price['month'];
$price = number_format(collect($prices)->sum(), 2, '.', '');


You can use Eager Loading to load your relationships along with the services query to turn those 15 extra queries into one extra query.

Code examples in the linked docs should be enough to get you started.