I am trying to remove user IDs in a column for this table called Offer. User IDs are inserted in as a string like '1,2,3,4'. I have a select multiple which contains a list of approved users for the offer in the table. I am having trouble removing an array of userId's from this column field. My code for the function is below:
Public function removeAccess(Offer $offer, Request $request)
{
$this->validate($request, [
'private_access' => 'required',
]);
$current_allowed = array($offer->private_allowed);
$remove_allowed = $request->private_access;
$allowed = array_diff_key($current_allowed, array_flip($remove_allowed));
$offer->private_access = $allowed;
$offer->save();
return redirect()->back()->with('status', 'Publisher(s) successfully removed from private access.');
}
What am I doing wrong? I thought I would do a loop of each of the $request->private_access
and then check if it's in the array, if it is, deletes it. I found another code elsewhere online to do it how I have it displayed, but still running into issues with it deleting all of them even if I select only 1 from the < select multiple > input.
Question Solved! After more research and another 24 hours of on-and-off figuring this out, below is the function now that works for the task.
Important for anyone encountering the same issue, in the select, I had to add [] behind the name-"name[]" to put the values into an array> I also had to convert my array in the database to be similar to the array the multiple select comes with.
$this->validate($request, [
'private_access' => 'required',
]);
$current_allowed = explode(',', $offer->private_access);
$remove_allowed = $request->private_access;
$filtered = array_diff($current_allowed, $remove_allowed);
$allowed = implode(',', $filtered);
$offer->private_access = $allowed;
$offer->save();
return redirect()->back()->with('status', 'Publisher(s) successfully removed from private access.');
}
return redirect()->back()->withErrors('An error has occurred.');