Get request data for fillable attributes

Quick tip of the day, how to auto map the data from the Request object to the Eloquent Model in Laravel. Let’s take a look at this handy piece of code.

Model: Person.php

Code tip:

In order to get $fillable of the model, getFillable() is the method provided by Laravel. And if you want to retrieve a subset of the input data from the Request object, you may use the only() method.

$person = new Person();
$data = $request->only($person->getFillable());
$person->fill($data)->save();

Only accepts a single array or a dynamic list of arguments.

Example code from Laravel documentation.

Register Or Login to leave a comment.