Skip to content
Advertisement

Laravel – Eloquent – Dynamically defined relationship

Is it possible to set a model’s relationship dynamically? For example, I have model Page, and I want to add relationship banners() to it without actually changing its file? So does something like this exist:

JavaScript

Or something similar? As they are fetched using the magic methods anyway, perhaps I can add the relationship dynamically?

Thanks!

Advertisement

Answer

I’ve added a package for this i-rocky/eloquent-dynamic-relation

In case anyone still looking for a solution , here is one. If you think it’s a bad idea, let me know.

JavaScript

Add this trait in your model as following

JavaScript

Now you can use the following method to add new relationships

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement