I'm trying to use mass assignment. Yet I faced a little problem with uploading an image when attempting such method.
I added fillable property in News.php Model.
protected $fillable = ['title','content','image','status'];
My attempt using mass assignment
public function store(Request $request)
{
//Handle File upload
if($request->hasFile('image'))
{
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('image')->storeAs('public/news_images',$fileNameToStore);
}else
{
$fileNameToStore = 'noimage.jpg';
}
News::create(request(['title','content','image','status']));
return Redirect('/news');
}
the error I'm getting
SQLSTATE[HY000]: General error: 1364 Field 'image' doesn't have a default value (SQL: insert into
news
(title
,content
,status
,updated_at
,created_at
) values (Hello there !, what are you trying to do ?, 0, 2019-07-13 08:45:46, 2019-07-13 08:45:46)) Previous exceptions SQLSTATE[HY000]: General error: 1364 Field 'image' doesn't have a default value (HY000)
if there is another and easier way to upload an image using mass assignment. Please recommend.
This is an imperfect answer, since it does not use mass-assignment for the image.
$news = new News(request(['title', 'content', 'status']));
$news->image = $fileNameToStore;
$news->save();
To fully use mass-assignment to set the new image path from the request, you would have to modify the FileBag of the request to somehow contain a 'fake' file that has the new path. This is probably not a good practice, and unless absolutely necessary I would just use the way shown in the snippet above.