I have a relationship where a user has many emails, and an email belongs to one user. I define it like this in my message model :
public function users() {
return $this->belongsTo('App\User','sender_id','id');
}
Here is my controller :
$sender_name = Message::with('users')->get();
return view('admin.message.read',compact('message','sender_name'));
In my view, I do something like this :
@foreach($sender_name as $sender_names)
@php(
dd($sender_name)
)
{{$sender_name->name}}
@endforeach
So, here I have 2 questions:
- How do I retrieve the relation I defined in my view? Currently, I get an error that this property does not exist on collection !!!
- Do I need to define the opposite relation in the user's model like this? :
public function messages() {
$this->hasOne('App\Message','id','sender_id');
}
Here is the code around the view :
<div class="media-body">
<h6 class="media-heading">{{$message->title}}</h6>
<!-- sender name of Email-->
<div class="letter-icon-title text-semibold">
@foreach($sender_name as $sender_names)
{{$sender_names->users->name}}
@endforeach
<!-- sender name of Email-->
<!-- sender Email-->
<a href="#">jira@diakultd.atlassian.net</a>
</div>
<!-- sender name of Email-->
</div>
<!-- body of Email-->
<table width="600" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<td valign="middle" align="center" style="font-size: 40px; color: #ffffff; line-height: 50px; font-weight: 300;">
</td>
</tr>
</table>
<!-- /title -->