How to upload image in laravel 8

Created at 11-May-2021 , By samar

How to upload image in laravel 8

Good day, guys. In this post, we’ll look at how to solve the "How to upload image in laravel 8" programming puzzle.

There are lots of ways to upload images in Laravel. One of the most common ways is to use the move method in which we have to specify the destination folder and image name to upload images in the specified folder in Laravel.
  • Upload file in public directory using move method in Laravel

    // Inside controller’s method or any where you wish to use this code snippets
    
    $file = $request->file('file');
    $filename = time().'_'.$file->getClientOriginalName();
    $location = 'files';
    $file->move($location,$filename);
    

    This code snippet will help you to get the file using a request. After that, you can store the file in the specified folder using the move method in Laravel.

  • Upload file using move method with public_path in Laravel

    $imageName = time().'.'.$request->image->extension();  
    $request->image->move(public_path('images'), $imageName);
    

    You can also pass the public_path() as the destination to move method where to store images in Laravel. This code snippet first creates an image name with the current time and file extension method after that it moves the image to the images folder of the public directory with this particular name.

  • Image upload functionality with validation to the public folder in Laravel

    --PATH app\Http\Controllers\<YourController.php>
    public function fileUpload(Request $request) {
        
        $this->validate($request, [
            'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
    
        if ($request->hasFile('input_img')) {
            $image = $request->file('input_img');
            $name = time().'.'.$image->getClientOriginalExtension();
            $destinationPath = public_path('/images');
            $image->move($destinationPath, $name);
            return back()->with('success','Image Upload successfully');
        }
    }
    

    This code snippet helps you to upload image in the images directory which is inside of the public directory. It first validates the input file request and after that uploads to your public directory.

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.