Laravel Testing Tip: Reset UUID Creation

TL;DR: if you call Str::createUuidsUsing(…) in a test method, don’t forget to call Str::createUuidsNormally() later in that same method (or the tearDown method), or the rest of your test suite will continue to use that same UUID.

Laravel’s string helper provides a nice interface for generating uuids, as well as a nice way to fake the UUIDs during a test:

While this is very useful, I expected that it would reset between tests, similar to Queue::fake(), Http::fake(), etc.

However, because of how the Str helper generates UUIDs, whatever you provide will be used for the rest of the test run. If you have other tests or app code that expects a unique UUID each time Str::uuid() is used, you may get unexpected results.

There are a couple of options to work around this:

  1. After running the code that needs a UUID, call Str::createUuidsNormally() to reset the Str helper.
  2. If you don’t actually need the value of the UUID for testing, you can wrap your code in the freezeUuids() method instead. Once your code in the callback finishes running, the framework will call createUuidsNormally() to reset everything for you:

Laravel Tip: Generating Signed URLs with Ignored Parameters

TL;DR: don’t use ignored URL parameters when building signed URLs or the resulting signed URL will be invalid. Instead, manually append them to the resulting URL.

Laravel includes some really nice helpers for building signed URLs:

They allow you to generate a URL containing a signature that prevents anybody from modifying the URL to access something you didn’t intend (e.g., you could provide a signed URL for a specific post with ID 123; if somebody changed that ID to 124, then Laravel will display a 403 Signature Invalid error rather than happily displaying post 124).

Occasionally you may wish to ignore certain URL parameters when validating the signature (e.g., a pagination or print parameter).

In this case, you cannot include the ignored parameter when generating the signed URL, or the URL will be invalid.

Here’s an example. This route ignores the print parameter when verifying the signature:

If you generate a signed URL without the print parameter, it will be valid. But if you include print in the URL parameters for the helper method, the resulting signature will be invalid, because Laravel uses all of those parameters to generate the signature. Instead, just add the new parameter to the end of the resulting URL:

Note how examples 1 and 3 have the same signature; that is the signature that Laravel calculates when determining what the correct signature should be to verify that the URL has not been modified. The example 2 use print=true when generating the signature, but will remove that parameter when verifying the signature, so they don’t match.

Update: I submitted a PR to the framework to pass ignored parameters to the signed route methods to make this easier.