4

I am trying to delete any five rows from my users table. I used following code for that.

DB::table('users')->take(5)->delete();

But it deletes all rows in that table. How will I overcome this problem?

manoos
  • 1,675
  • 3
  • 21
  • 46

4 Answers4

4

You said you want to delete 5 rows randomly, in this case this will work, I've tested it:

DB::table('users')->whereIn('id', DB::table('users')->orderBy(DB::raw("RAND()"))->take(5)->lists('id'))->delete();

It will take 5 random IDs and then will delete rows with these IDs with just two queries:

select `id` from `users` order by RAND() asc limit 5
delete from `users` where `id` in ('786', '186', '82', '578', '232')
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
1

You can use rand() function and delete users this way

DB::table('users')->DB::table('users')->orderby(RAND())->take(5)->delete();
Amit Ray
  • 3,445
  • 2
  • 19
  • 35
0

You can use foreach

$users = DB::table("users")->orderBy(DB::raw("RAND()"))->take(5)->get();
foreach($users as $user){
    DB::table("users")->where("id", $user->id)->delete();
}
Andrii Lutskevych
  • 1,349
  • 13
  • 23
0
DB::table('users')->whereIn('id', DB::table('users')->take(5)->lists('id'))->delete();
Paul Androschuk
  • 796
  • 7
  • 9