I am trying to implement a created_by column in my users' table.
I created a migration file to add the new column to the users' table:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('created_by')->default(0);
});
}
I have a User model which has the following relationships:
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function createdBy()
{
return $this->belongsTo(self::class, 'created_by');
}
In the UsersController, I have this method:
public function view($id)
{
$user = User::with(['roles', 'createdBy'])->where('created_by', Auth::id())->find($id);
return $user;
}
When I return the user variable, I get this result:
Now, I want to access the value from "email" in "created_by". I tried to do this:
return $user->created_by
What I'm getting is 2 but what I want to get is "[email protected]".
I also tried return $user->created_by->email but it returned an error since the result I'm getting from return $user->created_by is just a number.
I want to fetch the email value "[email protected]".
CodePudding user response:
Please change the createdBy relationship function with the createdByUser.
here we just change the function name to avoid conflict between column name and relationship name.
public function createdByUser()
{
return $this->belongsTo(self::class, 'created_by');
}
so now, you can access like
$user->createdByUser->email
CodePudding user response:
According to your JSON response this should work:
$user[0]->created_by->email

