Danielius Danielius - 6 months ago 93
PHP Question

Laravel 5.2 Eloquent hasOne relationship doesn't work

I have relationship in my chat model

public function user() {
return $this->hasOne(User::class,'id','writers_id');

And want to use it in my controller. I tryed many ways, but no one worked. Just giving last try example (result - blank page).

print_r($chat = Chat::where('id', 1)->first()->user);

Can anyone help me? Thanks! I don't really understand that Eloquent, used simple DB query maker before, however someone said that I should do every database stuff in model. Is it correct? Sorry about my poor English!


First as mentioned by @Vohuman

return $this->hasOne('App\User', 'id', 'writers_id');

And when using it:

Chat::where('id', 1)->first()->user()->first()->attribute