skip to Main Content

In PHP / Laravel, I am looking for an easier way to do the following in one line:

$newItem = clone $item;
unset($newItem->property1);
unset($newItem->property2);

I know I can create a helper method for it, but maybe there is one in Laravel already and i wasn’t aware of.

2

Answers


  1. $newItem = clone $item;
    unset($newItem->property1, $newItem->property2);
    

    you can also define a __clone method in your object

    public function __clone(): void
    {
        unset($this->property1, $this->property2);
    }
    

    and if your $item is a model you can do:

    $newItem = $item->replicate(['property1', 'property2']);
    
    Login or Signup to reply.
  2. There sure is a one liner and is mostly only useful for scenarios where you want to unset multiple properties.

    Convert the object to an array via typecasting, filter the keys that are required and cast them back to an object.

    <?php
    
    $newItem = (object)(array_filter((array)$item, fn($k) => !in_array($k, ['property1', 'property2']), ARRAY_FILTER_USE_KEY ));
    
    var_dump($newItem);
    

    Live Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search