Users table
- id
- name (string)
Visits table
- id
- user_id
- viewer_id
I want to get a list of visits with the linked username for a given user (in this case id = 1)
$visits = \Visits::where(['user_id' => 1])->with('user')->get();
this is my visits model:
class Visits extends Model
{
protected $table = 'visits';
public function store(Request $request)
{
$visits = new Visits;
$visits->save();
}
public function user()
{
return $this->belongsTo('User', 'viewer_id');
}
}
this is my User model
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function store(Request $request)
{
$user = new User;
$user->save();
}
}
it returns the data but the "user" is null
I think you need to change your code a little bit. Please try the following:
public function user()
{
return $this->belongsTo('App\User', 'viewer_id', 'id');
}
$visits = \Visits::where(['user_id' => 1])->with('user')->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With