Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Sven0188's avatar

Laravel Schema Design :: Conditional Relationship

Good day,

I am facing a strange challenge. The project that I am working on currently requires me to define a relationship between tables that is based on a value on a parent table.

In other words. For example:

Departments
    ->Machines
        ->Tools
            ->Parts
            

but on the Departments table I have a field/attribute: "HasTools" which will store 0 / 1. When the value is 1 then the relationship should change as follows:

Departments
    ->Machines
        ->Parts

in short, when the Department.HasTools = 1 then the "TOOLS" relationship changes - the Part belongsTo Machines and Departments.

  1. I am not sure if this is the best practice in terms of DB design and can one have/define conditional relationships
  2. How will I implement and handle this conditional relationship in Laravel / Eloquent?

The company have 3 different types of Departments. All the entities, except for this one relationship, are the same. Should I opt for separate set of tables for each Department of can I force them together in this structure?

Above all of this is a Company table. Departments will belong to a main Company table.

0 likes
2 replies
Screenbeetle's avatar

Hello

I think to get help you'll need to expand a bit on the details.

What tables are you thinking of setting up (or trying to decide on)? What exactly is the relationship you want to define between each?

Classically you'd have each of your entities set up with their own tables - company, departments, machines, parts etc - then establish the relation between each. e.g.

company has many departments | department belongs to company
department has many machines | machine belongs to department
machine has many parts | part belongs to machine

I'm not sure exactly what you're trying to do but my intuition is that if you set up each table separately, with appropriate relations, you'll be able to work your conditions into your app.

Sven0188's avatar

Hi there - thanks for reply. Yes indeed each entity will be own table.

But the relationship between two tables will change based on the department table value.

So I will have Departments table. This table have a property namely "hastools". If this is set to 1 then the relationship of its child tables will change. A level does not apply.

If "hastools" is set to 0 then a different relationship between its children tables will apply.

In my message above I have tried to show the 2 different relationships. In first example there is a Tools table and in the second example the Tools table is not applicable

Please or to participate in this conversation.