0👍
✅
Make fields nullable in database. Then fields will be NULL
if you doesn’t set them.
Migration:
public function up()
{
Schema::create('insights', function (Blueprint $table) {
$table->id();
$table->string('body')->nullable();
$table->string('head1')->nullable();
$table->string('paragraph1')->nullable();
$table->string('head2')->nullable();
//...etc
$table->timestamps();
});
}
And you can do it without errors:
public function store() {
$insight = new Insight();
$insight->save();
}
DB result:
mysql> select * from insights;
+----+------+-------+------------+-------+---------------------+---------------------+
| id | body | head1 | paragraph1 | head2 | created_at | updated_at |
+----+------+-------+------------+-------+---------------------+---------------------+
| 1 | NULL | NULL | NULL | NULL | 2022-02-22 07:38:58 | 2022-02-22 07:38:58 |
+----+------+-------+------------+-------+---------------------+---------------------+
1 row in set (0.00 sec)
0👍
Try this:
public function store(Request $request)
{
// validate your compulsory field here.
$insight= new Insight();
foreach($request->all() as $key => $value){
$insight[$key] = $value;
}
unset($insight[_token]); // if that's your csrf name
if($request->hasFile('image')){
$file = $request->file('image');
$file_name = time(). '.' . $file->getClientOriginalName();
$file->move(public_path('img/'),$file_name);
$insight[image] = 'img/' . $file_name;
}
$insight->save();
return response()->json(['message'=>'Saved Successfully'],200);
}
Source:stackexchange.com