Hi everyone!
I have three tables: users, services, and job_posts, with the following structure:
users: id, full_name, role, email_verified_at
services: id, name
job_posts: id, user_id (fk), service_id (fk), title, created_at
Currently, I’m fetching jobs using the following Eloquent method:
JobPost::with('user', 'service')->get();
The result is something like this:
"data": {
"jobs": [
{
"id": 17,
"user_id": 112,
"service_id": 1,
"job_title": "Car Wash",
"location": "Somewhere in world",
"budget": 200,
"status": "pending",
"scheduled_time": "2024-11-06 15:24:30",
"job_description": "Some description here",
"created_at": "2024-11-26T13:48:16.000000Z",
"updated_at": "2024-11-26T13:48:16.000000Z",
"user": {
"id": 112,
"full_name": "Abdullah",
"email": "[email protected]",
"phone_number": "03001234587",
"role": "customer",
"location": "Somewhere in the world",
"business_information": null,
"profile_pic": null,
"status": "active"
},
"service": {
"id": 1,
"name": "Service name",
"description": "Some description here",
"created_at": "2024-11-26T12:26:12.000000Z",
"updated_at": "2024-11-26T12:26:12.000000Z"
}
}
]
},
"messages": []
}
However, I want to fetch the user_name (i.e., full_name) and service_name (i.e., name) directly in the job_posts result, and not as nested objects. Ideally, the result should look like this:
{
"data": {
"jobs": [
{
"id": 17,
"user_id": 112,
"service_id": 1,
"full_name": "Abdullah",
"service_name": "Service name",
"job_title": "Car Wash",
"location": "Somewhere in world",
"budget": 200,
"status": "pending",
"scheduled_time": "2024-11-06 15:24:30",
"job_description": "Some description here",
"created_at": "2024-11-26T13:48:16.000000Z",
"updated_at": "2024-11-26T13:48:16.000000Z"
}
]
},
"messages": []
}
I found a solution like this:
->join('services as s', 's.id', '=', 'jp.service_id')
->join('users as u', 'u.id', '=', 'jp.user_id')
->select('jp.*', 's.name as service_name', 'u.full_name as user_name')
->get();
However, it feels more like a raw SQL query, and I would prefer a more "Eloquent" approach that's easier to read and maintain. Is there a way to achieve this result using Eloquent while keeping it clean and expressive?
Thanks in advance!