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

giorg's avatar
Level 1

testing controller update

Hi, I have about a hundred tests working correctly, but this one is not:

public function testUpdate()
    {
        $this->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class);

        Auth::loginUsingId(8);

        $invoice = factory(Invoice::class)->create();

        $invoice->total = 'non prende';
        $response = $this->patch('invoices/' . $invoice->id, $invoice->toArray());

        $this->assertDatabaseHas('invoices', ['id' => $invoice->id, 'total' => 'non prende']);

        // dopo aver eliminato si è redirezionati alla lista
        $response->assertRedirect('invoices/index');
    }

result is:

Failed asserting that a row in the table [invoices] matches the attributes {
    "id": 340,
    "total": "non prende"
}

however on the frontend I can update invoices correctly. How can I find where the problem is?

Thanks a lot

0 likes
9 replies
Nakov's avatar

And what is the code in your controller handling this request? I doubt that the problem is in the way you try to update the $invoice maybe instead of this:

$invoice->total = 'non prende';
$response = $this->patch('invoices/' . $invoice->id, $invoice->toArray());

pass just the total as the parameter you want updated:

$response = $this->patch('invoices/' . $invoice->id, ['total' => 'non prende']);
giorg's avatar
Level 1

hey nakov, thanks for your answer. doing that produces exactly the same result, here is my controller:

public function update($id, Request $request)
    {
        $user = Auth::user();
        if ($user->can('admin')) {
            $invoice = Invoice::findOrFail($id);

            foreach ($invoice->rows as $row) {
                $row->delete();
            }

            if (is_array($request->due_date) && count($request->due_date) > 1) {
                foreach ($request->due_date as $k => $date) {
                    if ($date) {
                        $var = 'due_date' . ($k + 1);
                        $invoice->{$var} = $date;
                    }
                }
            } else {
                $invoice->due_date1 = $request->due_date;
            }

            $invoice->number = $request->number;
            $invoice->payment_way_id = $request->payment_way;
            $invoice->payment_type_id = $request->payment_type;
            $invoice->update($request->all());
            $invoice->save();

            if ($request->products and is_array($request->products)) {
                foreach ($request->products as $k => $product) {
                    $row = new InvoiceRow();
                    $row->code = $request->products[$k];
                    $row->description = $request->descriptions[$k];
                    $row->quantity = $request->quantities[$k];
                    $row->price = $request->prices[$k];
                    $row->invoice_id = $invoice->id;
                    $row->save();
                }
            }
            return redirect('invoices/index')->with(['message' => 'Fattura modifica con successo!', 'alert-class' => 'alert-success', 'user' => $user]);
        }
        return redirect('/')->with(['message' => 'Non hai i permessi!', 'alert-class' => 'alert-danger', 'user' => $user]);
    }

weird thing is, as I mentioned, that in the frontend all of this works, and I have a lot of other tests that with this very same code (I mean the update test) on different models, that work too... Thank you

mstrauss's avatar

There is a lot going on in your controller's update method. So, this could be getting caught in any number of places. But to focus on the test itself:

Perhaps the total property is a numeric field? And therefore it's not accepting your "non prende" input.

$invoice->total = 'non prende';

Can you share the output of the below before the test assertions?

dd($response)

Not sure the below line is adding any value in the test

Auth::loginUsingId(8);
giorg's avatar
Level 1

Hi @mstrauss and thanks for you answer. total is a varchar, so should be fine. Auth is needed because my whole application is password protected. And here is the dd output:

Illuminate\Foundation\Testing\TestResponse {#11283
  +baseResponse: Illuminate\Http\RedirectResponse {#11417
    #request: Illuminate\Http\Request {#11337
      #json: null
      #convertedFiles: []
      #userResolver: Closure($guard = null) {#11362
        class: "Illuminate\Auth\AuthServiceProvider"
        this: Illuminate\Auth\AuthServiceProvider {#10851 …}
        parameters: {
          $guard: {
            default: null
          }
        }
        use: {
          $app: Illuminate\Foundation\Application {#10882 …}
        }
        file: "./vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php"
        line: "85 to 87"
      }
      #routeResolver: Closure() {#11354
        class: "Illuminate\Routing\Router"
        this: Illuminate\Routing\Router {#10848 …}
        use: {
          $route: Illuminate\Routing\Route {#11020 …}
        }
        file: "./vendor/laravel/framework/src/Illuminate/Routing/Router.php"
        line: "650 to 652"
      }
      +attributes: Symfony\Component\HttpFoundation\ParameterBag {#11339
        #parameters: []
      }
      +request: Symfony\Component\HttpFoundation\ParameterBag {#11338
        #parameters: array:1 [
          "total" => "non prende"
        ]
      }
      +query: Symfony\Component\HttpFoundation\ParameterBag {#11345
        #parameters: []
      }
      +server: Symfony\Component\HttpFoundation\ServerBag {#11341
        #parameters: array:16 [
          "SERVER_NAME" => "aamscomm.test"
          "SERVER_PORT" => 80
          "HTTP_HOST" => "aamscomm.test"
          "HTTP_USER_AGENT" => "Symfony"
          "HTTP_ACCEPT" => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
          "HTTP_ACCEPT_LANGUAGE" => "en-us,en;q=0.5"
          "HTTP_ACCEPT_CHARSET" => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
          "REMOTE_ADDR" => "127.0.0.1"
          "SCRIPT_NAME" => ""
          "SCRIPT_FILENAME" => ""
          "SERVER_PROTOCOL" => "HTTP/1.1"
          "REQUEST_TIME" => 1564060420
          "PATH_INFO" => ""
          "REQUEST_METHOD" => "PATCH"
          "REQUEST_URI" => "/invoices/39"
          "QUERY_STRING" => ""
        ]
      }
      +files: Symfony\Component\HttpFoundation\FileBag {#11342
        #parameters: []
      }
      +cookies: Symfony\Component\HttpFoundation\ParameterBag {#11340
        #parameters: []
      }
      +headers: Symfony\Component\HttpFoundation\HeaderBag {#11343
        #headers: array:5 [
          "host" => array:1 [
            0 => "aamscomm.test"
          ]
          "user-agent" => array:1 [
            0 => "Symfony"
          ]
          "accept" => array:1 [
            0 => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
          ]
          "accept-language" => array:1 [
            0 => "en-us,en;q=0.5"
          ]
          "accept-charset" => array:1 [
            0 => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
          ]
        ]
        #cacheControl: []
      }
      #content: null
      #languages: null
      #charsets: null
      #encodings: null
      #acceptableContentTypes: null
      #pathInfo: "/invoices/39"
      #requestUri: "/invoices/39"
      #baseUrl: ""
      #basePath: null
      #method: "PATCH"
      #format: null
      #session: Illuminate\Session\Store {#11252
        #id: "khuLFKAr3gsviJ7WVmRvauwpn30tu2fkY3zLoC4C"
        #name: "set_intranet_session"
        #attributes: array:6 [
          "login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 8
          "_token" => "CuA6H5LJBBqFtL01aACpRrcoGv4pR1fxx5JKICzn"
          "message" => "Fattura modificata con successo!"
          "_flash" => array:2 [
            "new" => []
            "old" => array:3 [
              0 => "message"
              1 => "alert-class"
              2 => "user"
            ]
          ]
          "alert-class" => "alert-success"
          "user" => App\User {#11262
            #fillable: array:5 [
              0 => "firstname"
              1 => "lastname"
              2 => "enabled"
              3 => "email"
              4 => "password"
            ]
            #hidden: array:2 [
              0 => "password"
              1 => "remember_token"
            ]
            #connection: "mysql"
            #table: "users"
            #primaryKey: "id"
            #keyType: "int"
            +incrementing: true
            #with: []
            #withCount: []
            #perPage: 15
            +exists: true
            +wasRecentlyCreated: false
            #attributes: array:9 [
              "id" => 8
              "email" => "<my email>"
              "email_verified_at" => null
              "password" => "y$qDjhsl4dXRzllnuHbdJdz.3TLE5JDYEZnR0ERsfQRIRZle8P.38j2"
              "remember_token" => "xE1XPi3aEjEIWtZepjNaR7L7UmvFL8eHCr00CfNxWEloDmaPrBvhhwnpQ53P"
              "created_at" => "2019-05-03 17:15:58"
              "updated_at" => "2019-05-03 17:15:58"
              "firstname" => "Andrea"
              "lastname" => "Giorgini"
            ]
            #original: array:9 [
              "id" => 8
              "email" => "<my email>"
              "email_verified_at" => null
              "password" => "y$qDjhsl4dXRzllnuHbdJdz.3TLE5JDYEZnR0ERsfQRIRZle8P.38j2"
              "remember_token" => "xE1XPi3aEjEIWtZepjNaR7L7UmvFL8eHCr00CfNxWEloDmaPrBvhhwnpQ53P"
              "created_at" => "2019-05-03 17:15:58"
              "updated_at" => "2019-05-03 17:15:58"
              "firstname" => "Andrea"
              "lastname" => "Giorgini"
            ]
            #changes: []
            #casts: []
            #dates: []
            #dateFormat: null
            #appends: []
            #dispatchesEvents: []
            #observables: []
            #relations: array:1 [
              "permissions" => Illuminate\Database\Eloquent\Collection {#11427
                #items: array:1 [
                  0 => App\Permission {#11422
                    #fillable: array:2 [
                      0 => "name"
                      1 => "slug"
                    ]
                    #connection: "mysql"
                    #table: "permissions"
                    #primaryKey: "id"
                    #keyType: "int"
                    +incrementing: true
                    #with: []
                    #withCount: []
                    #perPage: 15
                    +exists: true
                    +wasRecentlyCreated: false
                    #attributes: array:5 [
                      "id" => 1
                      "slug" => "admin"
                      "name" => "Admin"
                      "created_at" => "2019-05-03 17:15:27"
                      "updated_at" => "2019-05-03 17:15:27"
                    ]
                    #original: array:7 [
                      "id" => 1
                      "slug" => "admin"
                      "name" => "Admin"
                      "created_at" => "2019-05-03 17:15:27"
                      "updated_at" => "2019-05-03 17:15:27"
                      "pivot_user_id" => 8
                      "pivot_permission_id" => 1
                    ]
                    #changes: []
                    #casts: []
                    #dates: []
                    #dateFormat: null
                    #appends: []
                    #dispatchesEvents: []
                    #observables: []
                    #relations: array:1 [
                      "pivot" => Illuminate\Database\Eloquent\Relations\Pivot {#11423
                        +incrementing: false
                        #guarded: []
                        #connection: "mysql"
                        #table: "users_permissions"
                        #primaryKey: "id"
                        #keyType: "int"
                        #with: []
                        #withCount: []
                        #perPage: 15
                        +exists: true
                        +wasRecentlyCreated: false
                        #attributes: array:2 [
                          "user_id" => 8
                          "permission_id" => 1
                        ]
                        #original: array:2 [
                          "user_id" => 8
                          "permission_id" => 1
                        ]
                        #changes: []
                        #casts: []
                        #dates: []
                        #dateFormat: null
                        #appends: []
                        #dispatchesEvents: []
                        #observables: []
                        #relations: []
                        #touches: []
                        +timestamps: false
                        #hidden: []
                        #visible: []
                        #fillable: []
                        +pivotParent: App\User {#11262}
                        #foreignKey: "user_id"
                        #relatedKey: "permission_id"
                      }
                    ]
                    #touches: []
                    +timestamps: true
                    #hidden: []
                    #visible: []
                    #guarded: array:1 [
                      0 => "*"
                    ]
                  }
                ]
              }
            ]
            #touches: []
            +timestamps: true
            #visible: []
            #guarded: array:1 [
              0 => "*"
            ]
            #rememberTokenName: "remember_token"
          }
        ]
        #handler: Illuminate\Session\FileSessionHandler {#11251
          #files: Illuminate\Filesystem\Filesystem {#10752}
          #path: "/Users/giorg/PhpstormProjects/aamscomm/storage/framework/sessions"
          #minutes: "120"
        }
        #started: false
      }
      #locale: null
      #defaultLocale: "en"
      -isHostValid: true
      -isForwardedValid: true
      basePath: ""
      format: "html"
    }
    #session: Illuminate\Session\Store {#11252}
    #targetUrl: "http://aamscomm.test/invoices/index"
    +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#11414
      #computedCacheControl: array:2 [
        "no-cache" => true
        "private" => true
      ]
      #cookies: array:1 [
        "" => array:1 [
          "/" => array:1 [
            "set_intranet_session" => Symfony\Component\HttpFoundation\Cookie {#11395
              #name: "set_intranet_session"
              #value: "eyJpdiI6IitDT1piTHFcLzNYYnR3S0lpRitnZVlBPT0iLCJ2YWx1ZSI6IjhpZWNROFBadnphOVRrMDlQcm9ZMVgzb2NiY3NHSEJvcE85WVVnaUhKMHNqXC9JRjVtc0Q5NWFaOWc2QnJROGVMIiwibWFjIjoiMDg0ZDVlMzY0MzAyM2M4ZjY5OGFkZjVjODllODc4OTIyMTZkZmI2YTlkYzU5MjZlY2I1YjcwNzkwYWYzZThhMSJ9"
              #domain: null
              #expire: 1564067620
              #path: "/"
              #secure: false
              #httpOnly: true
              -raw: false
              -sameSite: null
              -secureDefault: false
            }
          ]
        ]
      ]
      #headerNames: array:5 [
        "cache-control" => "Cache-Control"
        "date" => "Date"
        "location" => "Location"
        "content-type" => "Content-Type"
        "set-cookie" => "Set-Cookie"
      ]
      #headers: array:4 [
        "cache-control" => array:1 [
          0 => "no-cache, private"
        ]
        "date" => array:1 [
          0 => "Thu, 25 Jul 2019 13:13:40 GMT"
        ]
        "location" => array:1 [
          0 => "http://aamscomm.test/invoices/index"
        ]
        "content-type" => array:1 [
          0 => "text/html; charset=UTF-8"
        ]
      ]
      #cacheControl: []
    }
    #content: """
      <!DOCTYPE html>\n
      <html>\n
          <head>\n
              <meta charset="UTF-8" />\n
              <meta http-equiv="refresh" content="0;url=http://aamscomm.test/invoices/index" />\n
      \n
              <title>Redirecting to http://aamscomm.test/invoices/index</title>\n
          </head>\n
          <body>\n
              Redirecting to <a href="http://aamscomm.test/invoices/index">http://aamscomm.test/invoices/index</a>.\n
          </body>\n
      </html>
      """
    #version: "1.1"
    #statusCode: 302
    #statusText: "Found"
    #charset: null
    +original: null
    +exception: null
  }
  #streamedContent: null
}

thank you

giorg's avatar
Level 1

actually I've just realized the response says "invoice updated successfully", so why te test is failing...

mstrauss's avatar
mstrauss
Best Answer
Level 14

Is total in your $fillable property for the Invoice model?

1 like
giorg's avatar
Level 1

damn forgot that. Thanks a lot!!

1 like
giorg's avatar
Level 1

I use the latest, but in fact I do get 419 if I don't disable csrf check... I had a look all over the project and I don't understand why env is not testing when... well, testing :) I have this in my phpunit.xml:

<env name="APP_ENV" value="testing"/>

which should override all other settings... ty

Please or to participate in this conversation.