Image Upload Example In Laravel 11

  Mar 2024
  ITSolutionsGuides
  Category: Laravel
Image Upload Example In Laravel 11

Welcome To ITSolutionsGuides,


In Laravel 11, image uploads is crucial for modern web applications where user will upload the image through the input field. When the image is uploaded initialy we should validate the image uploaded and then we should move the uploaded image to new directory and then save the path of the directory with the file name in the database

With the advent of Laravel 11, the process of uploading images becomes even smoother. Whether you're a seasoned Laravel developer or just starting your journey, understanding image uploads is fundamental. In this example, we'll explore various aspects, including setting up routes, creating controllers, and implementing views for a seamless image upload experience.

Firstly, we'll configure routes to handle image upload requests. Then, we'll create a dedicated controller responsible for processing image uploads. Utilizing Laravel's eloquent models, we'll define the necessary database schema to store image information efficiently.

Next comes the frontend part, where we'll design an intuitive user interface for uploading images. With Laravel's Blade templating engine, we'll craft elegant views that allow users to select and preview images before uploading.

But wait, there's more! We'll enhance the user experience by implementing client-side validation and AJAX techniques for smoother interactions. Additionally, we'll cover techniques for displaying uploaded images dynamically, ensuring a visually appealing presentation of user-generated content.

Throughout this example, we'll adhere to best practices, ensuring security and performance considerations are prioritized. From sanitizing user inputs to optimizing image storage, you'll gain valuable insights into building robust image upload features in Laravel 11.

By the end of this tutorial, you'll be equipped with the knowledge and skills to implement advanced image upload functionality in your Laravel 11 projects. So let's dive in and unleash the full potential of Laravel for handling image uploads with finesse!

Let's Start Coding

Lets install new laravel 11 project using the following command,
laravel new image_upload

Then lets crearte the controller for uploading the file using the following artisan command,
php artisan make:controller ImageController


app/Http/Controllers/ImageController.php

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Illuminate\View\View;
use App\Models\Image;
use Illuminate\Http\RedirectResponse;
    
class ImageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(): View
    {
        return view('imageUpload');
    }
          
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
          
        $imageName = time().'.'.$request->image->extension();  
           
        $request->image->move(public_path('images'), $imageName);
        
        Image::create(['name' => $imageName]);
          
        return back()->with('success', 'Image uploaded successfully!')
                     ->with('image', $imageName); 
    }
}

Let's Create the Routes

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageController;
  
Route::get('image-upload', [ImageController::class, 'index']);
Route::post('image-upload', [ImageController::class, 'store'])->name('image.store');

Let's Create Blade File

resources/views/imageUpload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload Example In Laravel 11 - ITSolutionsGuides</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
        
<body>
<div class="container">
  
    <div class="card mt-5">
        <h3 class="card-header p-3"><i class="fa fa-star"></i> Image Upload Example In Laravel 11 - ITSolutionsGuides</h3>
        <div class="card-body">
  
            @session('success')
                <div class="alert alert-success" role="alert"> 
                    {{ $value }}
                </div>
                <img src="images/{{ Session::get('image') }}" width="40%">
            @endsession
            
            <form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data">
                @csrf
        
                <div class="mb-3">
                    <label class="form-label" for="inputImage">Image:</label>
                    <input 
                        type="file" 
                        name="image" 
                        id="inputImage"
                        class="form-control @error('image') is-invalid @enderror">
        
                    @error('image')
                        <span class="text-danger">{{ $message }}</span>
                    @enderror
                </div>
         
                <div class="mb-3">
                    <button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Upload</button>
                </div>
             
            </form>
        </div>
    </div>
</div>
</body>
      
</html>

Let's Start Coding

Lets run the project using the following artisan command,

php artisan serve

http://localhost:8000/image-upload

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides