Home > Software engineering >  How to get changed value using array_diff in laravel?
How to get changed value using array_diff in laravel?

Time:12-28

public function changeData(Request $request)
{
     $product = Product::where('_id', '=', $request->product['_id'])->first()->toArray();

        //result product : 
        // array(4) {
        //     ["_id"]=>
        //     string(24) "5fffc00df116005c724859f2"
        //     ["name"]=>
        //     string(6) "iphone"
        //     ["slug"]=>
        //     string(14) "product-iphone"
        //     ["status"]=>
        //     string(14) "1"
        // }


        // result $request->product :
        // array(4) {
        //     ["_id"]=>
        //     string(24) "5fffc00df116005c724859f2"
        //     ["name"]=>
        //     string(7) "samsung"
        //     ["slug"]=>
        //     string(15) "product-samsung"
        //     ["status"]=>
        //     string(14) "1"
        // }

        $diff = array_diff($request->product, $product);
        var_dump($diff);
}

ERROR: 'Array to string conversion'

If I use the :

$diff = array_diff(array_map('serialize',$request->product), array_map('serialize',$product));

Then it will return the following result:

 array(2) {
        ["name"]=>
        string(15) "s:6:"samsung";"
        ["slug"]=>
        string(25) "s:15:"product-samsung";"
      }

The results above are correct for what I need. But it shows "s:6: and "s:15: inside the result. Is there a way for these two to not appear. I just want to get the correct result eg name is samsung. Thank you.

CodePudding user response:

If you want to check which fields were updated, you can use isDirsty method. For example, you want to check if the user has changed the email, send an email verification:

if ($user->isDirty('email'))
{
    // Do something
}

Laravel document

CodePudding user response:

try this

$diff = array_diff(array_map('serialize', $request->product), array_map('serialize', $product));

$multidimensional_diff = array_map('unserialize', $diff);

print_r($multidimensional_diff);
  • Related