Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vandan's avatar
Level 13

laravel multiple table query issue

hello guys, i want output like

{
	"success": true,
	"message": "user job list",
	"data": [
		{
  			"id": 2,
  			"job_name": "electrian",
  			"user_id": 1,
 	 		"service_provider_ids": "28, 29",
  			"created_at": "2022-07-12T09:27:12.000000Z",
  			"updated_at": "2022-07-12T09:27:12.000000Z",
			"service_provider_ids: {
					{
						"id": 28,
						"name": "vandan",
					},
					{
						"id": 29,
						"name": "demo",
					}
			},
		}
	]
}

so guys i have set this type of response & i have query like this

	$spName = User::whereIn('id',$spIds)->get(); 
	$data = Postjob::where('user_id',$id)->get();
	$data["service_provider_ids"] = $spName;

but dont find any solution how to do it ?

0 likes
14 replies
vandan's avatar
Level 13

any one have any idea for this

frankielee's avatar

@vandan

Show the migrations and the relationships between the table User and Postjob?

Also, share the controller?

vandan's avatar
Level 13

@frankielee

//user model
public function postjobs()
{
   		return $this->hasMany(Postjob::class);
}

// postjob model
public function user()
{
   	 return $this->belongsTo(User::class,'user_id','id');
}

//controller
public function userJobList($id)
{
    $job = Postjob::where('user_id',$id)->first();
    if (is_null($job)) {
        return $this->sendError("Job not found.");
    }
    $data = Postjob::where('user_id',$id)->get(); 
 	$spName = User::whereIn('id',$spIds)->get();      
    return $this->sendResponse($data, 'user job list');
}
vandan's avatar
Level 13

@frankielee

 	public function userJobList($id)
	{
    	$job = Postjob::where('user_id',$id)->first();
    	if (is_null($job)) {
        	return $this->sendError("Job not found.");
    	}
    	$data = Postjob::where('user_id',$id)->get()->toArray();
   		$spIds = array_map('intval', explode(',', $job->service_provider_ids));          
        $spName = User::whereIn('id',$spIds)->get()->toArray();
		$data['sp_details'] = $spName;
        return $this->sendResponse($data, 'user job list');
	}
MichalOravec's avatar

You can't have the same key service_provider_ids twice in the object.

aliabdm's avatar

try this data = [ PostJob:where('user_id',$id)->get(), "service_provider_ids "=> $spName ]; return data;

1 like
vandan's avatar
Level 13

@aliabdm

{
	"success": true,
	"message": "user job list",
	"data": [
		{
			"id": 2,
			"job_name": "electrian",
			"user_id": 1,
 			"service_provider_ids": "28, 29",
			"created_at": "2022-07-12T09:27:12.000000Z",
			"updated_at": "2022-07-12T09:27:12.000000Z",
			"service_provider_ids: {					
		},
		{
				"id": 28,
				"name": "vandan",
		},
		{
			"id": 29,
			"name": "demo",
		}
	}
]

}

aliabdm's avatar

@vandan ok ? thats what you asked for , what , showed as a response for the code I wrote ?

Please or to participate in this conversation.