Home > Blockchain >  Passing multiple string as parameter through url in laravel to delete specific data from database
Passing multiple string as parameter through url in laravel to delete specific data from database

Time:01-06

I want to delete multiple string data that is passed by url separated by ','.

Scenario is :

http://127.0.0.1:8888/remove/lui,kui

Through this route lui and kui data that is value of name field in database will be deleted.

My web.php file

Route::get("/remove/{name}",[MyController::class,"remove"]);

MyController.php file

use App\Models\City;   
function remove($name){

}

Thanks,your suggestion will be helpful.

CodePudding user response:

You can accomplish this with the following:

//The string of names
$names = "cat,cat,cat,mouse,dog,rabbit";

//We break it down, seperate them by comma, then add them to an array
//After we will get the unique values only of that array
$arrayOfNames = array_unique(explode(',', $names));
    
//search in the name column for any of these values
//delete if found
//note that you can change the word "name" to any other column name
City::whereIn('name', $arrayOfNames)->delete();

If you have the softdelete trait in your model, and would like to hard delete its: https://laravel.com/docs/9.x/eloquent#soft-deleting

//search in the name column for any of these values
//hard delete if found
City::whereIn('name', $arrayOfNames)->forceDelete();

You can also do an update as well if that is something you are interested in the future:

//search in the name column for any of these values
//update if found
City::whereIn('name', $arrayOfNames)->update(['age' => 123, 'updated_at' => now()]);

Hope it works well for you :)

  • Related