laravel_blog_image

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

<?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.

Example code from Laravel documentation.
Author: Danyal
I'm a skilled programmer specializing in Vue.js/Nuxt.js for front-end development and PHP Laravel for back-end solutions. I have a strong focus on API design and development, complemented by experience in web server setup and maintenance. My versatile expertise ensures seamless creation and maintenance of web applications, covering everything from intuitive user interfaces to robust server-side functionality. Passionate about coding and driven by a lifelong learning mindset, I invite you to explore more at danyal.dk.