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.
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
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community