Home > Back-end >  How to return file image name in database after upload in Laravel 9?
How to return file image name in database after upload in Laravel 9?

Time:06-27

The image uploads fine, it moves to the required folder, but the path name is not being returned into my database, it stays null

Posts Controller

if($request->hasFile('image')) {
        $fileName = $request->file('image');
        $file_name = $fileName->getClientOriginalName();
        $formFields['image'] = $request->file('image')->store('img','public');
    }

Posts::create([
        'title' => $request->post('title'),
        'sub_title' => $request->post('sub_title'),
        'tags' => $request->post('tags'),
        'content' => $request->post('content'),
        'featured' => ($request->has('featured')) ? true : false,
    ]);

Image upload input

<div >
 <label for="image" >Image</label>
  <input type="file"  name="image">
   @error('image')
    <p >{{ $message }}</p>
   @enderror
</div>

CodePudding user response:

You must add filename field in your table, the file moves to the required folder but after that you must assign the filename in a filed in Posts table like this :

Posts::create([
    'title' => $request->post('title'),
    'sub_title' => $request->post('sub_title'),
    'tags' => $request->post('tags'),
    'content' => $request->post('content'),
    'featured' => ($request->has('featured')) ? true : false,
    'filename' => $file_name   // add this line
]);

CodePudding user response:

Take a look at the code used at this timestamp. Notice that he is adding the image from the $request to his $formFields array which is an array of validated $request fields before passing the $formFields array to the create method on the object. You need to replicate that process.

$formFields = [
    'title' => $request->post('title'),
    'sub_title' => $request->post('sub_title'),
    'tags' => $request->post('tags'),
    'content' => $request->post('content'),
    'featured' => ($request->has('featured')) ? true : false,
];

if ($request->hasFile('image')) {
    $formFields['image'] = $request->file('image')->store('img','public');
}

Posts::create($formFields);

Side note, I have omitted $request input validation but you'll want to perform validation on the $request inputs. Never trust input.

  • Related