Image Upload With Preview

version : Laravel 10
Post Time : 09-05-2024

Image Upload With Preview

install laravel
         - composer create-project --prefer-dist laravel/laravel:^10.0 laravel_demo

Create Image Controller  :
           - php artisan make:controller ImagesController

app/Http/Controllers/ImagesController.php

                                      
                                        

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class ImagesController extends Controller
{
   public function index()
   {
       return view('image_upload');
   }

   public function saveImages(Request $request)
   {
       $request->validate([
           'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
       ]);
       if($request->hasFile('image'))
       {
           $image = $request->file('image');
           if($image->isValid())
           {
               $image_name = time() . '_' . $image->getClientOriginalName();
               $image->move(public_path('admin/upload_image/'), $image_name);

               //Save the image path to the database using DB facade
               $save_flag = DB::table('images')->insert([
                   'image' => 'admin/upload_image/' . $image_name,
                   'created_at'=>date('Y-m-d H:i:s')
               ]);

               if ($save_flag) {
                   //Image saved successfully
                   return redirect()->route('images')->with('success', 'Successfully saved...!!');
               }else{
                   //Error saving image
                   return redirect()->route('images')->with('error', 'Something went wrong...!!');
               }
           }else{
               //Invalid image file 
               return redirect()->route('images')->with('error', 'Invalid image file...!!');
           }
       } else {
           //No file uploaded
           return redirect()->route('images')->with('error', 'No image uploaded...!!');
       }
   }
}

Carete image_upload blade file :-
resources/views/image_upload.blade.php

                                      
                                        

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
       <!-- Bootstrap CSS -->
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> 
   <style>
       .error{
           color:red;
       }
   </style>
</head>
<body>
   <div class="mb-3 row text-center">
       <h1>IMAGE UPLOAD</h1>
   </div>
   <form action="{{ route('saveImages') }}" method="POST" enctype="multipart/form-data">
       @csrf
       @if(Session::has('error'))
           <div class="alert alert-danger" id="success-alert">
               {{Session::get('error')}}
           </div>
       @endif
       @if(Session::has('success'))
           <div class="alert alert-success" id="success-alert">
               {{Session::get('success')}}
           </div>
       @endif
       <div class="mb-3 row text-center">
           <label class="col-sm-6 col-form-label text-end">Image : </label>
           <div class="col-sm-6 text-start">
               <input id="image_0" type="file" name="image" onchange="display_image(this,0);" style="display:none;">
                   <label for="image_0">
                       <img id="photo_preview_0" width="102" height="101" src="{{asset('admin/images/add_photo.png')}}">    
                       <span style="font-size:20px;"><i class="fa fa-plus-square"></i></span>
                   </label>   
               @error('image')
                   <label class="error">{{ $message }}</label>
               @enderror
           </div>
           <div class="mb-3 mt-4 row text-center">
               <div class="col-sm-12">
                   <button type="submit" class="btn btn-primary">Save</button>
               </div>
           </div>
       </div>
   </form>
   <script>
       function display_image(input,i)
       {
           if(input.files && input.files[0] && input.files[0].type.match('image'))
           {
               var reader = new FileReader();reader.onload=function(e)
               {
                   $('#photo_preview_'+i).attr('src',e.target.result);
               }
               reader.readAsDataURL(input.files[0]);
           }
       }
   </script>
</body>
</html>

routes/web.php

                                      
                                        

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImagesController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
   return view('welcome');
});

Route::get('/images', [ImagesController::class,'index'])->name('images'); 
Route::post('/saveImages/{id?}', [ImagesController::class, 'saveImages'])->name('saveImages');