XiaTesting's avatar

How to test to "delete multiple records"

Hi guys, recently I really enjoy test before code, however, I have a problem here: I want to test delete multiple records according to id(array), here is my test:

public function test_it_can_delete_multiple_events()
{

    Event::factory()->count(5)->create();

    $eventsIds = Event::inRandomOrder()
        ->limit(2)
        ->pluck('id')
        ->toArray();
    // $eventsIds = [20, 23];
    $events = Event::whereIn('id', $eventsIds)->get();
    
    $this->delete('/events', $eventsIds);

    $this->assertDeleted('events', $events);

}

My route:

Route::delete('/events', [EventController::class, 'destroyMultiple']);

Here is my controller:

public function destroyMultiple(Request $request)
{

    Event::destroy($request->array); // $request->array, here I don't know what it should be.

}

The issue is how can I get id from $request object, I am confused, there is no name attribute. Any help would be appreciated.

0 likes
1 reply
bugsysha's avatar
bugsysha
Best Answer
Level 61

Have you tried following?

$this->delete('/events', ['list' => $eventsIds]);

$this->assertDeleted('events', $events);

Then in the controller

public function destoryMultiple(Request $request)
{
  foreach($request->list as $eventId) {
    Event::delete($eventId);
  }
}

Please or to participate in this conversation.