Laravel 4 The eloquent ORM getting mutual relation through dynamic properties

I am trying to model a fairly simple relationship between the Users table and the User_profiles table. Each user has user_profile, so it is simple for one. According to the documents found @ http://four.laravel.com/docs/eloquent#one-to-one I added the following function to the user model:

public function user_profile() { return $this->hasOne('User_profile'); } 

and this relationship is defined in my User_profile model:

 public function user() { return $this->belongsTo('User'); } 

I am trying to access the controller as follows:

  // Get current user $user = User::find(Auth::user()->id); $profile = $user->user_profile; print_r($user); print_r($profile); echo "User name is: " . $user->user_profile->first_name . ' ' . $user->user_profile->last_name; 

Unfortunately, when printing, $ user displays the fields of the user model only fine, but does not show any traces of the relationship; $ profile is empty. The array of 'relationships' is also empty, which I assume should be populated.

I am trying to use "dynamic properties" as suggested here http://four.laravel.com/docs/eloquent#dynamic-properties

Otherwise, if I just leave:

 echo "User name is: " . $user->user_profile()->first()->first_name . ' ' . $user->user_profile()->first()->last_name; 

It works ... but I don't really like to do it.

Any suggestions?

+6
source share
1 answer

Ok, so the problem is with using underscores in class names. Laravel follows PSR 0 and 1, as described here .

What this means is, I needed to name my model class and file name UserProfile (although my MySql table was still "user_profiles"), and then updated my User model to have the userProfile () function.

As soon as I updated the naming, I was able to access the relationships automatically by doing something like:

 $user = Auth::user(); echo $user->userProfile->first_name; 
+7
source

Source: https://habr.com/ru/post/946367/


All Articles