Home > Blockchain >  Laravel reuse of variable with nested relationships does not keep original data
Laravel reuse of variable with nested relationships does not keep original data

Time:08-06

While trying to reuse a variable in two different classes, the first class affects the data of the variable passed to the second class.

Example of problem:

class SampleA
{
    public function __construct($products)
    {
        // Has 3 rows since it's the first class being called
        unset($products[0]);
    }
}

class SampleB
{
    public function __construct($products)
    {
        // Should have 3 rows, only has 2
        unset($products[1]);
    }
}
    
$collection = \App\Models\Products::with('barcodes')->with('stock')->limit(3)->get(); // 3 rows for test purposes

$first = new SampleA($collection);
$second = new SampleB($collection);

// The $collection should have 3 rows and only has 1
print_r($collection); 

What have I tried without success:

Use of collect:

$collection = \App\Models\Products::with('barcodes')->with('stock')->limit(3)->get();
$copyCollectionFirst = collect($collection);
$copyCollectionSecond = collect($collection);

$first = new SampleA($copyCollectionFirst);
$second = new SampleB($copyCollectionSecond);

Use of clone:

$collection = \App\Models\Products::with('barcodes')->with('stock')->limit(3)->get();
$copyCollectionFirst = clone $collection;
$copyCollectionSecond = clone $collection;

$first = new SampleA($copyCollectionFirst);
$second = new SampleB($copyCollectionSecond);

Use of replicate:

$collection = \App\Models\Products::with('barcodes')->with('stock')->limit(3)->get();
$copyCollectionFirst = [];
$copyCollectionSecond = [];

foreach ($collection as $row)
{   
    $copyCollectionFirst[] = $row->replicate();
    $copyCollectionSecond[] = $row->replicate();
}

$copyCollectionFirst = collect($copyCollectionFirst);
$copyCollectionFirst = collect($copyCollectionSecond);

$first = new SampleA($copyCollectionFirst);
$second = new SampleB($copyCollectionSecond);

Whatever I do in the SampleA class, it will affect the SampleB class variable data.


What works:

Query multiple times the database:

$collectionFirst = \App\Models\Products::with('barcodes')->with('stock')->limit(3)->get();;
$collectionSecond = \App\Models\Products::with('barcodes')->with('stock')->limit(3)->get();;

$first = new SampleA($collectionFirst);
$second = new SampleB($collectionSecond);

Is there any way to avoid query DB multiple times? In my case this is important, since I might have thousands of records & use it more than 2 times.

CodePudding user response:

try

$collection = \App\Models\Products::with('barcodes')->with('stock')->limit(3)->get()->toArray();
$first = new SampleA(collect($collection));
$second = new SampleB(collect($collection));

CodePudding user response:

Solved.

Solution:

$copyCollectionFirst = unserialize(serialize($collection));
$copyCollectionSecond = unserialize(serialize($collection));
  • Related