0
votes

I want to upload images with laravel:I created the field in mysql:

imagepath varchar 250

Created the form:

<form  method="post" id="formId" action="/ticket" enctype="multipart/form-data">
    {{ csrf_field() }}
    <div class="form-group ">...other fields
       <div class="form-group">
           <input type="file" class="form-control-file" name="imageFile" id="imageFile" aria-describedby="fileHelp">
       </div>

In my controller:

public function store(Request $request)
{
    $fileName = request()->imageFile->getClientOriginalExtension();
    dd($fileName);//echos ".jpg"
    $tickes = Users::create(['imagePath' => $fileName]);
}

However my db is always null!I want to store it in my public/storage folder in Laravel. Please help!

2
append imagePath to $fillable in User modelAlihossein shahabi
@Alihosseinshahabi omg I totally forgot to update my model,but I still dont think it it right?now it saves it my db but its like this 1528305497.jpgRandomUser

2 Answers

2
votes

you can use this code for upload image to `public/storage/ directory :

if ($request->hasFile('input_img')) {
    if($request->file('input_img')->isValid()) {
        try {
            $file = $request->file('input_img');
            $name = rand(11111, 99999) . '.' . $file->getClientOriginalExtension();

            # save to DB
            $tickes = Users::create(['imagePath' => 'storage/'.$name]);

            $request->file('input_img')->move("storage", $name);
        } catch (Illuminate\Filesystem\FileNotFoundException $e) {

        }
    }
}
0
votes
  1. This code is only saving the file extension, not the image path.
  2. You need to save the file to storage before your database can get a path to it. Laravel has really good documentation and this link will help you figure this out. https://laravel.com/docs/5.6/filesystem