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


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());

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

Example code from Laravel documentation.
Author: Danyal
I'm skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting