Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Henrykarn's avatar

Unittesting with request and session in Laravel 5.7.15

I would like to create a unit-test for a method in a model-class.

When I catch an Exception in this method I create a suitable errormessage and put this into the session.

    public function dbdelete(Request $request, $grund)
    {
...
        try {
...
        }
        catch (\Exception $e) {
...
              $request->session()->put("asset_message", $message);
...
        }
}

I managed to create a request, put some data into it and call my models method. But as soon as my method wants to put the message into the session I get this exception 'Session store not set on request.'

I allready spent a lot of time searching the web how to initialize a session in the request.

Is there anybody out there who knows how to solve this problem?

0 likes
1 reply
mstrauss's avatar

In the unit test, are you using the WithoutMiddleware trait? If so, that may be your issue, as I believe the web middleware is needed to get/set session state/data.

Please or to participate in this conversation.