Reputation: 5014
I have two models and two tables. First model name Inbox
with database structure:
And second model name is StudentData
with database structure:
And I will return with route('/sended')
all mesages using my method for get needed messages:
public function getMessages($message_type = "new")
{
$user_id = Auth::user()->id;
$inbox = new Inbox();
$paginate = 3;
switch ($message_type) {
case 'sended':
$messages = $inbox->where('sender', $user_id)
->where('trashed_in_sender', 0)
->where('show_in_sender', 0)
->orderBy('created_at', 'desc')
->paginate($paginate);
break;
default:
return abort(404);
break;
}
return $messages;
}
And I have methods in my model Inbox
:
public function messageSender()
{
return $this->belongsTo("App\StudentData", 'sender');
}
public function messageRecipient()
{
return $this->belongsTo("App\StudentData", 'recipient');
}
When I call in view $message->messageSender
in result given NULL. Why I can't get data using sender id
from inboxes
table in student_datas
table
Upvotes: 4
Views: 146
Reputation: 1037
So, I have a few questions....
1) How exactly does your User and StudentData models interact? It kinda seems strange to have 2 models with what seems to be a 1:1 relationship?
Why not just use a User model?
(Do you even have a User model or am I misinterpreting things?)
2) I think your direction is wrong... if you already have a User model, try to get the sent messages from there. I will give you an example.
Let's say you have a User model and a Inbox model, where you have a "sender" and "recipient", which both have an id of the User model.
So in the Inbox model we have:
public function messageSender()
{
return $this->belongsTo("App\User", 'sender');
}
public function messageRecipient()
{
return $this->belongsTo("App\User", 'recipient');
}
But why not go from the other direction? We can write the relationships in the User model like
public function sentMessages()
{
return $this->hasMany("App\Inbox", 'sender');
}
public function receivedMessages()
{
return $this->hasMany("App\Inbox", 'recipient');
}
Now you can get all sent messages (i.e. all messages where the user is the sender) just by using
$user->sentMessages
and operate on that. Or you could even set up a special helper relation (my name sucks, find a better one... just for example)
public function unreadSentMessages()
{
return $this->hasMany("App\Inbox", 'sender')
->where('trashed_in_sender', 0)
->where('show_in_sender', 0)
->orderBy('created_at', 'desc');
}
and can either use $user->sentMessages for all his messages or $user->unreadSentMessages for only the ones you need in your case.
Upvotes: 1