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

mbo's avatar
Level 3

Replace within a collection

I'm trying to do the following:

I'm running a query and getting a collection. See below:

\MacBook-Pro:ligplaats $ php artisan Update:AutoTextDps
Illuminate\Database\Eloquent\Collection {#41546
  #items: array:1 [
    5 => App\service {#16047
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:11 [
        "id" => 3
        "service_parent_id" => 2
        "service_status_id" => 1
        "service_object" => 1
        "service_name" => "AAA"
        "service_discription" => ""
        "service_value" => "1.00"
        "service_weighting" => "1.00"
        "service_ranking" => "1.00"
        "created_at" => null
        "updated_at" => null
      ]

No i want to replace the "service_name" - AAA with BBB

How can i best do this?

I tried to do this by:

     $value = $dp->services->whereIN('id',[5,3,9,10,11])->implode('service_name',', ');

And than:

 $kind = str_replace($value,'AAA'  , 'BBB');

This works. But i want to be able to replace more values ($value contains of more values that have to be replaced)

How can i best solve this?

thanks for the help.

0 likes
3 replies
kevinbui's avatar

What about this:

return $services->each(function ($service) {
    if ($service->name === 'AAA') {
        $service->name = 'BBB';
    }

    // You can do whatever else you want in this closure.
});
neilstee's avatar

@mbo str_replace can use multiple values for example:

$search = ['AAA', 'aaa', '111'];
$replace = ['BBB', 'bbb', '222'];
$kind = str_replace($search, $replace, $value);
teos_97's avatar
$lookup = [
'AAA' => 'BBB',
'CCC' => 'DDD',
]; //etc...

if(array_key_exists($service->name, $lookup) {
	$service->name = $lookup[$service->name];
} 

even extract it in a helper function like so :

function replaceModelColumnValues($lookupTable, $model, $field, $shouldSave = false) {

	if(array_key_exists($model->$field, $lookupTable) {
		$model->$field = $lookupTable[$model->$field];
		if($shouldSave) {
			$model->save();
		} 
	}
	return $model;
}


in your controller or wherever you have the collection

$lookup = [
'AAA' => 'BBB',
'CCC' => 'DDD',
]; //you could have this in a config or a const in the model class or just like this

$modifledServicesCollection = $servicesCollection->map(fn($service) => replaceModelColumnValues($lookup, $service, 'service_name', true);

Please or to participate in this conversation.