I want to store file in public folder and save that’s name to MySQL database, database does not create record for file_name
column.
When I post file then file moves to folder but database does not create record of file name, please help.
-
This is my controller store function
$request->validate([ "title"=>"required", "description"=>"required|string", "file_name"=>"nullable" ]); if($request->has('file')){ $file=$request->file('file'); $extension=$file->getClientOriginalExtension(); $fileName=time().'.'.$extension; $path='postFiles'; $file->move($path,$fileName); } $post=Post::create([ 'title'=> $request->title, 'description'=> $request->description, 'file_name'=>$fileName, 'user_id'=>auth()->user()->id ]); $post->save();
-
this is database record
id title description user_id file_name created_at updated_at 1 title: 34636sdfg... 2 NULL 2024-04-16 09:06:41 2024-04-16 09:06:41
3
Answers
if ($request->hasFile(‘file_name’))
The issue seems to be related to the file name being saved to the database. The variable $fileName is only defined conditionally when a file is uploaded. If no file is uploaded, $fileName will not be set, and an attempt to use it in the Post::create() method will result in an error.
Here’s a revised version of your code to ensure that the file name is saved to the database only when a file is uploaded: I have added code to this image.
$fileName is initialized to null before checking if a file is uploaded.
We use public_path(‘postFiles’) to specify the path to the postFiles directory inside the public folder.
We conditionally add the file_name key to the $postData array only if a file was uploaded.
This should resolve the issue you’re facing with storing the file name in the database.
From my experience, you need to use the
hasFile()
method on the request object