PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, February 4, 2022

[FIXED] Laravel Model::create mass assignment not working for columns with null as default value

 February 04, 2022     eloquent, laravel, laravel-8     No comments   

Issue

I have a table in my db where some columns are nullable and of course have null as default value.

In my controller, I use Model::create($request->all()) to save. While it saves the data, the nullable columns were not populated with any value, still null.

Perhaps, does making it ->nullable() in migration the issue?

If not, can someone explain why the nullable columns were not populated with their corresponding values? and how do I address the problem?


Solution

Take look at the Mass Assignment Documentation

So, to get started, you should define which model attributes you want to make mass assignable. You may do this using the $fillable property on the model

You have to add $fillable property to your model, especially when you are using Model::create($request->all()).

public $fillable = [];

For example:

public $fillable = ['some_property', 'some_other'];

Now, if you will call create method, 'some_property' and 'some_other' will be assigned.

Also, you can use $guarded which says that all properies are mass assignable and nothing is guarded

public $guarded= [];

Don't use $guarded if you are going to create model by passing $request->all() to create method



Answered By - Malkhazi Dartsmelidze
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing