'Accessing an item from a key value pair object derived from a parent relationship
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]".
Solution 1:[1]
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
Solution 2:[2]
According to your JSON response this should work:
$user[0]->created_by->email
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mitesh Rathod |
| Solution 2 | Biswajit Biswas |

