I could find a proper solution in the forum for my problem.
In my Laravel nova I have some Course Categories and if the user wants to delete some of them I create an action to delete the data but before that I check if these course categories have some courses in it. This works everything fine. I'll go trough a foreach loop for every checked Categorie but if some are deletable and some not the foreach breaks out and stops. I think its because the return statements. But how can i get this return
`Action::message('Deleted!');`
OR
Action::danger('The Course Category "'.$model->name.'" could not be deleted, it may contains some Courses!');
done without breaking out of the loop and continue ?
CodePudding user response:
Set a variable before the loop - let's call it "alldeleted".
$alldeleted = true;
And also set a blank array for categories that cannot be deleted :
$undeletedcategories = array();
If, during the loop, one of the categories cannot be deleted, note that by setting alldeleted to be false, adding the category name to the array, and using continue to go to the next element in the loop :
$alldeleted = false;
$undeletedcategories[] = $model->name;
continue;
Then, at the end of the process, look at whether $alldeleted is true or not and compose your response accordingly :
if($alldeleted) {
// return your "all deleted alright" status message here.
} else {
// Return the "these categories weren't deleted" status message here.
}
CodePudding user response:
Thanks for the fast help Giles, I was able to solve my issue. I added another foreach to fill all the Category names in the Message.
$alldeleted = true;
$undeletedcategories = [];
$categorie = [];
foreach ($models AS $model)
{
$course = Course::where('category_id', $model->id)->count();
if($course === 0)
{
$model->delete();
}
else {
$alldeleted = false;
$undeletedcategories[] = $model->name;
}
}
if($alldeleted === true) {
return Action::message('Deleted all selected Courses successfully!');
} else {
foreach($undeletedcategories AS $cat)
{
$categorie[] = $cat;
}
return Action::danger('The following Course Category "'.implode(", ",$categorie).' " could not be deleted, it may contains some Courses!');
}