Answer the question
In order to leave comments, you need to log in
Laravel Don't live so hard. Eloquent ORM - One to One?
There is a table of users and a table with their photos.
There are two models. User and Photo_user
In the User model:
public function GetUserPhoto () {
return $this->hasOne('App\Models\Photo_user');
}
echo \App\Models\User::find(Auth::user()->id)->GetUserPhoto->name;
public function GetUserPhoto () {
return Photo_user::where('user_id', $this->id)->first()->name;
}
Answer the question
In order to leave comments, you need to log in
In the model
public function getPhotoNameAttribite()
{
return $this->GetUserPhoto->name;
}
Do you even have the slightest understanding of what MVC is?
Are you really displaying THIS in the view?
First, Auth::user()
it already contains the User model object. Why get the id from the model and query the database again?
Instantly, the output is reduced to the following form:
Let's go further.
In the User model, we create a relationship CORRECTLY:
public function userPhoto() {
return $this->hasOne('App\Models\Photo_user'); // Советую называть модели как нормальные люди. UserPhoto - как вариант. Забудьте нижнее подчеркивание, весь Laravel - это CamelCase.
}
public function getUserPhotoAttribute(){
if ( ! array_key_exists('userPhoto', $this->relations))
$this->load('userPhoto');
$related = $this->getRelation('userPhoto')->first();
return ($related) ? $related->name : false; // выводим userPhoto->first()->name
}
{{ Auth::user()->userPhoto }}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question