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 image to storage directory (storage/app/)

    $path = $request->file('photo')->store('avatars', 'public');
    return $path;
    

    Here is photo is file name and avatars is folder inside storage/app/public directory and you don't have to create the avatars directory. It will be created automatically after executing the above script. Data (images, files, documents) stores in storage/app/public directory in not directly accessible so you have to create a symlink by running php artisan storage:link command. Now you can access file by using below code snippt in any blade.php file.

    <img src="{{ asset('/storage/avatars/5AGu1cRdR73BQ3J1voZKStb47lhItNawm9FwUW5J.png') }}" />
    
    Here is full demo code to insert image in storage directory and creating a symlink and displaying the image in blade.php file.
    

    add code to web.php file (routes/web.php)

    Route::get('/image-upload', [TestController::class, 'uploadImage'])->name('uploadImage');
    Route::post('/image-upload', [TestController::class, 'saveUploadImage'])->name('uploadImageSave');
    //create symlink 
    Route::get('/storage-link', function(){
        Artisan::call('storage:link'); 
    });
    

    Add controller using php artisan make:controller TestController command and paste below code in it

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Models\User;
    use App\Mail\TestMail;
    use Illuminate\Support\Facades\Mail;
    
    class TestController extends Controller
    {
        public function uploadImage(){
            return view('image');
        }
    
        public function saveUploadImage(Request $request){
            $path = $request->file('photo')->store('avatars', 'public');
            return view('image', compact('path'));
        }
    }
    

    Create view file image.blade.php in resources/views directory

    <!doctype html>
    <html lang="en">
        <head>
            <!-- Required meta tags -->
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <!-- Bootstrap CSS -->
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
            <title>Hello, world!</title>
        </head>
        <body>
            
            @if(isset($path))
                <img src="{{ asset('/storage/'.$path) }}" />
            @endif
            <div class="container">
                <form  action="{{ route('uploadImageSave') }}" method="POST" enctype="multipart/form-data">
                        @csrf
                       <div class="form-group">
                            <label>File browser : </label>
                            <div class="custom-file">
                                <input type="file" class="custom-file-input" id="customFile" name="photo">
                                <label class="custom-file-label" for="customFile">Choose file</label>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
    
            <!-- Option 1: Bootstrap Bundle with Popper -->
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
    
            <!-- Option 2: Separate Popper and Bootstrap JS -->
            <!--
            <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>
            -->
        </body>
    </html>
    

    Now first visit http://localhost:8000/storage-link url to create a symlink for storage directory.

    After creating symlink you can visit http://localhost:8000/image-upload url to upload image and after that you will be redirected same page with displaying image in your view file.

  • Upload file in public directory using move method in Laravel

    // Inside controller&rsquo;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.