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
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Person extends Model
{
protected $fillable = ['name', 'age', 'gender', 'email', 'mobile'];
}
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.