DEV Community

Muhamad Sulaiman
Muhamad Sulaiman

Posted on

Inverse of hasManyThrough Laravel

Currently, I'm developing a Learning Management System called Kelas Design. And today my task is to count how many Episodes do the Series have and vice-versa.

So I do the logic using Laravel Built-in Eloquent : Has Many Though. What's my logic look like is :

Image description

So I will get the Episodes data through Section. That's fine. But how about getting the Episode and which Series it's belongs to?

I realized that, in Laravel documentation, there's no instruction about Inverse of Has Many Through or Has One Through.

And since they don't provide that instruction, so I do need to create it manually. Usually if I faced a situation like this, I always reverse engineer the logic.

For example, Laravel has the built-in function such as Has Many Through & Has One Through.

So what I do is in Episode Model, I create method and returning Has One Through. If you're thinking about using belongsTo, you are wrong.

And this is my logic :

Image description

By default, you can just passed two (2) arguements if you are following Laravel convention. But in my case, If you just passed the two arguements, it will print an Error. Which the system cannot find the column you wanted.

With the extra arguements, you can search more depth. The third arguement is called $first_key and the fourth is $second_key.

Adding this, will allow the system to search more deep in your Database. And Eventually, will return you a data that you need. The third and fourth arguements is not nessasary an 'id'. It can be something else.

That's all, I hope my solution also can solve your situation like me also. If you have a better approach to do the inverse, please do comment below :)

PS : I've stumble upon one package name staudenmeir/belongs-to-through. Tested it and based on what I read at the files, this package also will solve my problem. However, I do not seek something overkill like this. Look at my solution, compared to this package. Even though the syntax is much cleaner, but I still need to download the package that have many files. And that I do not want to.

By the time I wrote this blog, this package has issue. Please refer to Github Issue

Top comments (2)

Collapse
 
victorheid profile image
Victor Heid

Hi

I believe that what you suggest doesn't work - it 'works' by chance as when testing the ids will be 1 on all models, so it manages to link them.

When you sen't 'id' as the two arguments you are linking the wrong column of each model to each other, you are basically selecting a Series that has the same id as the Section your episode is linked to.

Collapse
 
msulaimanmisri profile image
Muhamad Sulaiman

The code is already in production and nothing has broken so far. I hope you are right. Thanks for the explanation