Skip to content
Advertisement

PHPUnit assertDatabaseHas with Laravel and Inertia

I have a Laravel 8 setup that utilises Intertia.js. I’m trying to test my post routes to store new resources and want to assert that the database has the new record stored, using the assertDatabaseHas() method.

Controller.php

public function store(SlotCreate $request): RedirectResponse
    {
        $slot = CreateSlot::dispatchNow($request);

        return redirect()->back()->with([
            'message' => 'Slot Created Successfully.',
            'slot' => new SlotResource($slot)
        ]);
    }

CreateSlotTest.php

public function testCreateSlot()
    {
        $response = $this->actingAs($this->teamAdminOne)->post('/slots', [
            'start_time' => '09:00',
            'end_time' => '10:00',
            'max_bookings' => 3
        ]);

        $response->assertStatus(302);

        $this->assertDatabaseHas('slots', [
            'id' => ???
            'team_id' => $this->teamAdminOne->currentTeam(),
            'start_time' => '09:00',
            'end_time' => '10:00',
            'max_bookings' => 3
        ]);
    }

When I debug the session I can see the slot that I added to the with() method but I can’t figure out how to access it.

I’d like to know if I’m returning the slot correctly in the controller and if yes, how do I access the response to assert if the database has this record?

Advertisement

Answer

Actually when you call redirect()->with(), it adds the variables into the session by calling the session()->flush() method. So in this case you can retrieve the variables via IlluminateSupportFacadesSession facade.

$slot = IlluminateSupportFacadesSession::get('slot')
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement