I want to access user_projects
from the following data
{
"id": 1,
"title": "Random",
"description": "Null",
"client_id": 3,
"deadline": "2023-10-13 18:30:05",
"status": "Proposal",
"created_at": "2023-10-13T05:26:17.000000Z",
"updated_at": "2023-10-13T05:26:17.000000Z",
"user_projects": [
{
"id": 1,
"name": "Rosendo Pfannerstill III",
"email": "[email protected]",
"email_verified_at": null,
"is_client": 0,
"address": null,
"country": null,
"phone_number": null,
"profile_image": null,
"created_at": "2023-10-13T05:15:47.000000Z",
"updated_at": "2023-10-13T05:15:47.000000Z",
"pivot": {
"project_id": 1,
"user_id": 1
}
},
{
"id": 22,
"name": "MukeshPrakash",
"email": "[email protected]",
"email_verified_at": null,
"is_client": 0,
"address": null,
"country": null,
"phone_number": null,
"profile_image": null,
"created_at": "2023-10-13T05:17:12.000000Z",
"updated_at": "2023-10-13T05:17:12.000000Z",
"pivot": {
"project_id": 1,
"user_id": 22
}
}
]
}
I am getting this output from the following controller function
public function clientsAndUsers($id)
{
$projects = Project::with('userProjects')->find($id);
echo $projects;
}
This data is coming from a belongsToMany
eloquent relationship. Instead of using echo
, here I gotta send the data to a view but I have no idea how to access the users_projects
.
I have tried this
$projects->user_projects
And this
$projects["user_projects"]
If I put this on a loop like this
foreach($projects as $project) {
echo $project;
}
It strangely returns 1
thrice. I have no idea why, and both are returning nothing so I can’t put that in a loop as well.
So kindly help me access it and also explain a bit.
2
Answers
You access it through your Eloquent relationship that you’ve eager loaded (using
with('userProjects')
):When Laravel converts models to json output, it automatically converts the relationship names to
snake_case
, which is why theuserProjects
relationship is output using theuser_projects
key. So, even though the json is showinguser_projects
, that key doesn’t actually exist on the model object, which is why you can’t access it like you’ve tried.Your question is not clear, but if i am getting you right. you want to access the user_projects array in the data set.
you can do
Then in your blade view;