So I have been working on a project where 2 types of users register. 1. Company 2. Distributor
I have created modules for both and they both have separate authentication modules created using passport.
All working fine and now I want to add a feature which allow to send messages from Companies to Distributor or vise versa.
Here are my migrations:
1. messages
id
messages
parent_message_id(to handle message thread)
2. fromables (polymorphic relationship to handle FROM which user the message was sent)
id
message_id
fromable_id
fromable_type ( ‘AppCompany’ or ‘AppDistributor’ )
3. toables (polymorphic relationship to handle TO which user the message was sent)
id
message_id
toable_id
toable_type ( ‘AppCompany’ or ‘AppDistributor’ )
Below is how the relationships are defined in Models:
- Company model and Distributor model
public function messages_sent() { return $this->morphToMany('AppMessage', 'fromable'); } public function messages_received() { return $this->morphToMany('AppMessage', 'toable'); }
- Message model
public function from_company() { return $this->morphedByMany('AppCompany', 'fromable'); } public function from_distributor() { return $this->morphedByMany('AppDistributor', 'fromable'); } public function to_company() { return $this->morphedByMany('AppCompany', 'toable'); } public function to_distributor() { return $this->morphedByMany('AppDistributor', 'toable'); }
And below is how I access the messages sent and received inside company and distributor controllers.
$user = $request->user(); $messages_received = $user->messages_received; $messages_sent = $user->messages_sent;
This works fine all the way upto here.
Now the issue is, when I run below code to receive all the messages
$messages_received = $user->messages_received;
It returns all messages but it doesn’t return who sent them. Ofcource messages_received uses ‘toable’ relation. And sender ID is under ‘fromable’ relation.
Here is where I am not sure how to get the sender details along with all the messages when done $user->messages_received
How can I do that? If there is any different approach to implementing this messaging system, do let me know aswell.
Thank You.
Advertisement
Answer
From what I understand you should be able to do $user->messages_received->load('from_company')
to get the relation to which company the message is sent.