Laravel updateOrInsert processing foreach
P粉538462187
P粉538462187 2024-02-17 19:25:47
0
1
325

I have multiple columns in DB and I need to populate the values ​​in these fields. To achieve this, I use a foreach loop.

$update = [];

foreach ($userPermissions->getPermissionNames() as $t)
{
    if (in_array($t, $permissions))
    {
        $update[] =  [$t => 1];
    }
    else{
        $update[] = [$t => 0];
    }
}

The output of this array is here:

array:2 [▼
  0 => array:1 [▼
    "is_admin" => 1
  ]
  1 => array:1 [▼
    "is_something_else" => 1
  ]
]

But when it goes into updateOrInsert it fails because the array is not structured correctly.

UserPermission::updateOrInsert(['user_id' => $user->id], $update);

How to insert these dynamic values ​​into table?

P粉538462187
P粉538462187

reply all(1)
P粉296080076

How about building a simple array with keys and values?

foreach ($userPermissions->getPermissionNames() as $t)
{
    // Cast the bool to an int
    $update[$t] = (int) in_array($t, $permissions);
}

It should produce something like,

[
    'is_admin' => 1,
    'is_something_else' => 1,
]
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!