How to upload Images using LARAVEL 10

Spread the love

Hello Guys,

Learn how to upload images using Laravel 10 with this comprehensive guide. This article provides a step-by-step Laravel 10 image upload example. Discover how to utilize Laravel 10 to seamlessly upload images to your database. Follow our detailed instructions on how to upload and display images in Laravel 10.

This tutorial will cover the creation of two routes: one for the get method, responsible for rendering forms, and another for the post method, used for uploading image code. We’ve crafted a user-friendly form featuring a file input, allowing you to effortlessly select an image for upload to the “images” directory within the public folder.

Hence, to acquire and upload Images using LARAVEL 10 application, just follow the steps below.

Step 1: Install Laravel 10

While it’s optional, you can go ahead and execute the following command if you haven’t yet established your Laravel application:

Also Read: how to use Cron Job Task Scheduling using LARAVEL 10

composer create-project laravel/laravel example-app

Step 2: Create a Controller

In this tutorial, we’ll guide you through creating a brand-new ImageController, complete with the essential index() and store() methods. These methods are responsible for rendering views and managing picture storage.

To build your ImageController, simply follow these instructions:

Now, let’s update the code in your controller file as illustrated below.

app/Http/Controllers/ImageController.php
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\View\View;
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);
      
        /* 
            Write Code Here for
            Store $imageName name in DATABASE from HERE 
        */
        
        return back()
                    ->with('success', 'You have successfully upload image.')
                    ->with('image', $imageName); 
    }
}
Store Image in Storage Folder

Also Read: How to Get Database Name using Laravel?

$request->image->storeAs('images', $imageName);

// storage/app/images/file.png
Store Image in Public Folder
$request->image->move(public_path('images'), $imageName);

// public/images/file.png
Store Image in S3
$request->image->storeAs('images', $imageName, 's3');

Step 3: Create and Add Routes

To effectively handle GET and POST requests for rendering views and storing images, navigate to your “routes/web.php” file and incorporate these routes.

Also Read: how to use Flash Message using LARAVEL 10

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageController;
  
/* 
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::controller(ImageController::class)->group(function(){
    Route::get('image-upload', 'index');
    Route::post('image-upload', 'store')->name('image.store');
});

Step 4: Create a Blade File

Concluding the process involves crafting the ‘imageUpload.blade.php’ file, which includes generating a form containing a file input button. Simply replicate the provided code snippet and insert it into your file.

resources/views/imageUpload.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 Image Upload Example - itcodestuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
      
<body>
<div class="container">
       
    <div class="panel panel-primary">
  
      <div class="panel-heading">
        <h2>Laravel 10 Image Upload Example - itcodestuff.com</h2>
      </div>
 
      <div class="panel-body">
       
        @if ($message = Session::get('success'))
        <div class="alert alert-success alert-block">
            <button type="button" class="close" data-dismiss="alert">×</button>
                <strong>{{ $message }}</strong>
        </div>
        <img src="images/{{ Session::get('image') }}">
        @endif
      
        <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">Upload</button>
            </div>
       
        </form>
      
      </div>
    </div>
</div>
</body>
    
</html>

Now Run Your Laravel App:

Execute the following command and hit Enter to initiate your Laravel application after successfully completing all required steps.

Also Read: How to Create Custom Helper Functions in LARAVEL 10

php artisan serve

Please access the designated URL through your web browser to see the results of the application.

http://localhost:8000/image-upload

Uncover the ultimate insights in our collection, your gateway to the best Laravel blog content.

Leave a Comment