Skip to content

Commit 9e3ed25

Browse files
authored
Updated file-upload.md to also add a note of when this part is relevant
1 parent 8d56834 commit 9e3ed25

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

symfony/file-upload.md

+10-4
Original file line numberDiff line numberDiff line change
@@ -491,17 +491,23 @@ If you're not using `autowiring` and `autoconfiguring`, don't forget to register
491491

492492
For resolving the file URL, you can use a custom normalizer, like shown in [the previous example](#resolving-the-file-url).
493493

494-
## Uploading Files on Your User Entity
494+
### Uploading Files on your User Entity
495495

496-
If you’d like to add file-upload support directly to your `User` entity (rather than a dedicated `MediaObject`), there’s one extra “gotcha” you must handle:
497-
Symfony’s session storage will try to serialize your entire `User` object (including any `File` instance you’ve attached), and `File` is not serializable by default.
496+
If you’d like to add file-upload support directly to your `User` entity (rather than a dedicated `MediaObject`), there’s one extra “gotcha” you may have to take care of.
497+
498+
> [!NOTE]
499+
> If you only expose file uploads through API Platform’s endpoints (e.g. POST /media_objects or POST /users/{id}/avatar), you don’t need any special serialization hooks and you can ignore this part.
500+
> This part is only relevant if you try to attach an `UploadedFile` or `File` object directly to your `User` entity in a non-API context (for example via a Symfony form controller where the `User` is stored in the session).
501+
502+
Symfony’s session handler will attempt to serialize the entire `User` object when it stores your `User` in the session (for example via the Security token in a Symfony form controller).
503+
Since `File` is not serializable by default, you’ll encounter:
498504

499505
To avoid PHP errors like:
500506
```
501507
Serialization of 'Symfony\Component\HttpFoundation\File\File' is not allowed
502508
```
503509

504-
you need to implement both the old `\Serializable` interface **and**, depending on the PHP version, the new `__serialize()` / `__unserialize()` magic methods on your `User`, limiting serialization to just scalar fields (`id`, `email`, `password`, etc.).
510+
To fix this, you need to implement both the old `\Serializable` interface **and**, starting with PHP 7.4+, the new `__serialize()` / `__unserialize()` magic methods on your `User`, limiting serialization to just scalar fields (`id`, `email`, `password`, etc.).
505511
Symfony will then happily keep your `User` in the session while VichUploaderBundle handles the file itself.
506512

507513
```php

0 commit comments

Comments
 (0)