Image Upload In Laravel
To implement image upload in Laravel, you can follow these general steps:
STEP 1: Create Laravel Project
first, create a Laravel project, and then follow the given steps.
laravel new laravel-image-upload
STEP 2: Go To Project Directory
cd laravel-image-uploadSTEP 3: Now Create Blade File
Now create a blade file for writing front-end code from where you can upload the file. Here we overwrite the welcome.blade.php file. You can copy the below code and paste in the welcome.blade.php file.
<!DOCTYPE html><html lang="en"><head><title>Laravel Image Uploadtitle><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script></head><body><div class="container d-flex mt-5"><div class="card"><div class="card-body"><form action="/upload-image" method="post" enctype="multipart/form-data">@csrf@error('image')<div class="alert alert-danger show">{{ $message }}</div>@enderror<input type="file" name="image" class="form-control" required><button class="btn btn-primary mt-2">Upload</button></form></div>@if(session('uploaded_img'))<div class="card-footer"><div class="alert alert-success show">{{ session('success_msg') }}</div><img src="{{session('uploaded_img')}}" height="50px" width="50px"></div>@endif</div></div></body></html>
STEP 4: Make Controller
Run the below artisan command for creating a controller in the Laravel app where you write image uploading logic.
php artisan make:controller ImageController
STEP 5: Create uploadImage function in the Image Controller.
Create an uploadImage function in ImageController and write login for uploading the image.
1. first validate the type of uploaded image using the Laravel request validator.
2. After successful validation fetch image data and store in variable.
3. Generate a unique name for the image.
4. Store your file in a particular directory.
5. After storing the file you can save the image URL in the database for further use.
namespace App\Http\Controllers;use Illuminate\Http\Request;class ImageController extends Controller{public function uploadImage(Request $request){$request->validate(['image' => 'required|mimes:png,jpg,jpeg|max:2048']);try{$image=$request->image; //OR $request->file('image');$image_name=time().'-'.$image->getClientOriginalName();$uploaded_path=public_path('uploads/images/');$image->move($uploaded_path,$image_name);$img_path=asset('uploads/images/'.$image_name);return back()->with('success_msg','image upload successfully')->with('uploaded_img',$img_path);}catch(Exception $e){return $e;}}}
STEP 6: Create routes
use Illuminate\Support\Facades\Route;use App\Http\Controllers\ImageController;Route::get('/', function () {return view('welcome');});Route::post('/upload-image',[ImageController::class,'uploadImage'
STEP 7: Run the project and check the output
php artisan serveOUTPUT


