DEV Community

El Morjani Mohamed
El Morjani Mohamed

Posted on • Updated on

๐Ÿš€ Laravel Tip๐Ÿ’ก: Extract Validated Input Elegantly

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();
Enter fullscreen mode Exit fullscreen mode

Using safe() makes your code cleaner and ensures you're only working with validated data, enhancing both security and code clarity.

Top comments (1)

Collapse
 
xwero profile image
david duymelinck

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.