Support the ongoing development of Laravel.io →
Database Eloquent

Hi, I currently have a table which serves as a central link table for many-many relations between several other tables. These relationships are defined generically like this:

    public function linked($moduleClass)
    {
        $instance = new $moduleClass;
        
        return $this
            ->belongsToMany($moduleClass, 'linkster', $this->linksterKey, $instance->linksterKey);
    }

This works fine for just accessing the collection of linked records, for instance:

Contact::first()->linked('Org')->get();

However, I can't eager load using with(). So, is there a way to either pass in arguments to relations in with(), or better yet, defining a default behavior for undefined relationships? I tried implementing the second option using __call(), but I'm not sure how to properly override it without stepping on Eloquent's __call() method.

Thanks in advance for any help.

edit: I figured out a way to do it but I'll leave this up in case someone has a better way to do it, or if this is the best way to do it then it's up here if anyone is looking to do something similar.

    // probably not the exact implementation I'll use, but this is the idea.
    protected $modules = ['orgs','contacts'];
    
    public function __call($name, $args)
    {
        if (in_array($name, $this->modules)) {
            return $this->linked(studly_case(str_singular($name)));
        }
        
        return parent::__call($name, $args);
    }
Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

dtaub-mms dtaub-mms Joined 30 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.