Categories
Laravel

Safe Mass Assignment in Laravel

Rather than explicitly assigning each allowed property to a Model (to avoid passing user input directly through) you can use the validated data to safely mass assign.

Re this tweet:

The $request->validate() method will return the keys of valid data (and redirect on failure).

<?php
$data = $request->validate([
...$rules])

$model->fill($data);

However if you accept input in the request that needs to be validated, but should not end up on the model this approach won’t work.