Support the ongoing development of Laravel.io →
posted 10 months ago
0

Nobody has any ideas? :)

0

To retrieve all three relationships (ModelA, ModelB, ModelC) for a User in Laravel using Eloquent's morphMany relationship, you can define custom methods in your User model. Here is an example: In your User model, define the morphMany relationships for ModelA, ModelB, and ModelC:


class User extends Model
{
    // ...

    public function modelA()
    {
        return $this->morphMany(ModelA::class, 'user');
    }

    public function modelB()
    {
        return $this->morphMany(ModelB::class, 'user');
    }

    public function modelC()
    {
        return $this->morphMany(ModelC::class, 'user');
    }

    // ...
}```

Next, create a custom method in the User model to retrieve all the models at once:

```use Illuminate\Database\Eloquent\Model

class User extends Model
{
    // ...

    public function allModels()
    {
        return $this->modelA->concat($this->modelB)->concat($this->modelC); 
    }

    // ...
}

Now, you can use $user->allModels to retrieve all the related models for a user.

Last updated 9 months ago.
0

Thanks for the reply. This is my code but doesn't seem to work.

public function devices_digital_matter(){
        return $this->belongsToMany(Device::class,env('DB_DIGITAL_MATTER_DATABASE').'.device_user');
    }
public function mobile_devices(){
        return $this->hasMany(\App\Models\Integration\Mobile\Device::class);
    }
public function all_devices(){
        return $this->mobile_devices->concat($this->devices_digital_matter);
    }

Am i missing something? The error is App\Models\User::all_devices must return a relationship instance

Last updated 9 months ago.
0

Got it, needed $user->all_devices() not $user->all_devices

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Joel Ireland d3v Joined 25 May 2023

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.

© 2024 Laravel.io - All rights reserved.