I'm trying to figure out how to eager load data from a related table. I have 2 models Group and GroupTextPost.
Group.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Group extends Model
{
protected $table = 'group';
public function type()
{
return $this->hasOne('\App\Models\GroupType');
}
public function user()
{
return $this->belongsTo('\App\Models\User');
}
public function messages()
{
return $this->hasMany('\App\Models\GroupTextPost');
}
}
GroupTextPost.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class GroupTextPost extends Model
{
protected $table = 'group_text_post';
public function user()
{
return $this->belongsTo('\App\Models\User');
}
public function group()
{
return $this->belongsTo('\App\Models\Group');
}
}
What I'm trying to do is eager load the user when fetching group text posts so that when I pull the messages the user's name is included.
I've tried doing it like so:
public function messages()
{
return $this->hasMany('\App\Models\GroupTextPost')->with('user');
}
... and calling like so:
$group = Group::find($groupID);
$group->messages[0]->firstname
But I get an error:
Unhandled Exception: Call to undefined method Illuminate\Database\Query\Builder::firstname()
Is this possible to do with Eloquent?
$m = $group->messages()->get();and then$m[0]->user[0]->first_name;- Dev