How to model a dependency graph in Laravel

I am stuck modelling the following relationship in a new application: A Module can require (many) other Modules.

In Laravel I added the Module model and a ModuleRequirement model with its migrations. The second one has a foreign id field for the module it belongs to:

Schema::create('module_requirements', function (Blueprint $table) {

    // How to reference other modules?

The relationship itself is defined by:

// Module.php

public function moduleRequirements()
    return $this->hasMany(ModuleRequirement::class);

This method returns a collection of ModuleRequirements as expected. Unfortunately in order to get the real Module objects I need a foreach loop and build my own collection. I wonder if there is a simpler and faster solution. The perfect way I could imagine is sth. like $module->moduleRequirements returning a collection of the actual models instead of its ids.


My understanding that a module has relation with other modules in the same table. you should use many to many relationship ,in that case you will not need a model for ModuleRequirement just a pivot table would be sufficient.

In your case module_requirements would act as the pivot table and you just need to change the relation in Module.php to :-

 public function moduleRequirements(){
        return $this->belongsTomany(Module::class,"module_requirements", 'module_id', 'requires');

the migration should be something like :-

Schema::create('module_requirements', function (Blueprint $table) {