As developers, we often need to extract only a few items from a validated request. Instead of manually unsetting or filtering, Laravel provides a clean and efficient way to do this using the safe() method. Hereโs how:
// Extract only specific fields
$validated = $request->safe()->only(['name', 'email']);
// Extract all fields except specified ones
$validated = $request->safe()->except(['name', 'email']);
// Extract all validated input
$validated = $request->safe()->all();
Using safe() makes your code cleaner and ensures you're only working with validated data, enhancing both security and code clarity.
Top comments (1)
If you look at the documentation you will see that the part that make the
safe
function work is a FormRequest class that is type hinted.So your example with the Request typehinting will not validate any input.