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

Deekshith's avatar

Pluck and chunk with relationship

I have three tables like below,

user_nominations

id,election_id,post_id,

user_nomination_details

id, user_nomination_id,nominee_id,status

users

id, name,email,phone_number

so models are like below,

UserNomination.php

public function nominationdetails()
    {
      return $this->hasMany('App\Models\UserNominationDetail','user_nomination_id','id')->orderBy('id','DESC');
    }

UserNominationDetail.php

public function nomineedetails()
    {
      return $this->belongsTo('App\Models\User','nominee_id','id');
    }

So now i want to fetch all nomineedetails phone numbers in chunk array like below,

[
  [
    "7417417417",
    "9696969696",
    "7897897899",
    "8528528528"
  ],
  [
    "9879879879",
    "9639639639",
    "9977887788",
    "8527419639"
  ]
]

I have a query like below,

$nomination = UserNomination::where('user_id',uid())->where('nomination_code',$nominationcode)->where('election_id',$electiondetail->id)->where('submitted',0)->first();

 $nominationdetailsget = $nomination->nominationdetails;

foreach ($nominationdetailsget->chunk(4) as $chunk) {
      foreach ($chunk as $nominee) {
        if($nominee->nomineedetails)
        {
          
		$phonenumber = $nominee->nomineedetails->phone_number;
       //here i want to make to create a format which i mentioned above.

        }
          
      } 
    }

But now i want to send sms by passing multiple number with comma separated so i want to use like below,

foreach($mobilechunks as $mobiledata)
    {
      $this->sendSms($mobiledata->implode(','),$message);
    }

But the problem is i am not getting how to get the data in chunk format using relationship like below,

[
  [
    "7417417417",
    "9696969696",
    "7897897899",
    "8528528528"
  ],
  [
    "9879879879",
    "9639639639",
    "9977887788",
    "8527419639"
  ]
]
0 likes
2 replies
neilstee's avatar
neilstee
Best Answer
Level 34

@deekshith try this:

$mobilechunks = [];
foreach ($nominationdetailsget->chunk(4) as $chunk) {
	$mobileNumbers = [];
      foreach ($chunk as $nominee) {
        if($nominee->nomineedetails)
        {
          
		$phonenumber = $nominee->nomineedetails->phone_number;
       //here i want to make to create a format which i mentioned above.
		$mobileNumbers[] = $phonenumber;

        }
          
      } 
	$mobilechunks[] = $mobileNumbers;
    }

// $mobilechunks should have to format you need here

Please or to participate in this conversation.