Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Laravel 10 Image Upload with Preview Example

Laravel 10 Image Upload: A Comprehensive Tutorial

Aman Jain, October 23, 2023March 16, 2024

Laravel 10, renowned for its efficiency and simplicity, offers a seamless solution for handling image uploads in web applications. In Laravel 10 Image Upload tutorial, we will guide you through the process of uploading and displaying images using the robust features of Laravel 10. Whether you are a beginner or an experienced Laravel developer, this tutorial will help you implement image uploading effortlessly.

Prerequisites for Laravel 10 Image Upload

Before we dive into the tutorial, let’s ensure that we have the necessary prerequisites in place:

  1. Basic understanding of Laravel and PHP.
  2. Laravel 10 installed on your system.
  3. A Laravel project set up.
  4. A working database connection.

Table of Contents

Prerequisites for Laravel 10 Image Upload
Step 1: Create a Migration and Model
Step 2: Create Routes and Controllers
Step 3: Create the Image Upload Form
Step 4: Handle Image Uploads
Step 5: Test the Image Upload Functionality
Additional Tips and Tricks

Step 1: Create a Migration and Model

To begin, we need to create a table to store our image data. Let’s generate a migration file using the following command:

php artisan make:migration create_images_table

Now navigate to the database/migrations folder and open the newly created migration file. Inside the up() method, add the required columns for the images table:

public function up()
{
    Schema::create('images', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('image_path');
        $table->timestamps();
    });
}

Once you have defined the columns, run the migration command to create the table:

php artisan migrate

To interact with the images table, we need to create an Image model. Run the following command to generate the model:

php artisan make:model Image

Step 2: Create Routes and Controllers

To handle image uploads, we’ll create a dedicated controller. Execute the following command to generate the controller:

php artisan make:controller ImageController

Now, let’s define the routes for our image upload functionality. Open the routes/web.php file and add the following routes:

use App\Http\Controllers\ImageController;

Route::get('/images', [ImageController::class, 'index']);
Route::post('/images/upload', [ImageController::class, 'store']);

Step 3: Create the Image Upload Form

In this step, we’ll create a form that allows users to upload images. Inside the resources/views directory, create a new file called imageUpload.blade.php. Copy and paste the following code into the file:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 Image Upload Example</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</h2>
            </div>
            <div class="panel-body">
                <form action="{{ url('/images/upload') }}" 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')
                            <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>

Step 4: Handle Image Uploads

In the ImageController we created earlier, let’s define the index() and store() methods. The index() method will render the image upload form, while the store() method will handle the image upload logic.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class ImageController extends Controller
{
    public function index(): View
    {
        return view('imageUpload');
    }

    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);

        // Store $imageName in the database

        return back()
            ->with('success', 'You have successfully uploaded an image.')
            ->with('image', $imageName);
    }
}

Congratulations! You have successfully implemented image uploads in your Laravel 10 application. Now let’s test it out.

Step 5: Test the Image Upload Functionality

To view the image upload form, visit the following URL in your web browser:

http://localhost:8000/images

Select an image file and click the “Upload” button. If the image is valid and within the specified size limits, it will be stored in the public/images directory. The image file name will be saved in the database along with other relevant information.

Additional Tips and Tricks

  • To store images in a different folder, modify the public_path('images') part of the store() method in the ImageController.
  • To store images in cloud storage services like Amazon S3, refer to the Laravel documentation for the necessary configuration and code adjustments.

That’s it! You now have a fully functional image upload feature in your Laravel 10 application. Feel free to customize and enhance it according to your specific requirements. Happy coding!

Related

Laravel Laravel 10 imagelaraveklaravellaravel 10phpupload

Post navigation

Previous post
Next post

Related Posts

Php Image Validation in laravel 8

How to use image validation in Laravel 8 with example

November 21, 2021January 26, 2022

Laravel provides multiple ways to validate a form or a image in form with it’s own validation library. In this tutorial we will learn about the image validation for specific extension and file size. In this tutorial i will use a simple form and a image file input field to…

Read More
Javascript Laravel Ajax Autocomplete Using Select2

Laravel Customized Autocomplete Options Using Select2

July 18, 2022July 18, 2022

In this article we will learn to use Laravel Customized Autocomplete Options Using Select2. Select2 is useful when we want live search of bulk data or to convert the existing select boz with multi features like search, multi select and options customizations. Autocomplete search is mostly work of javascript and…

Read More
Php How to Get Current Date, Time and Day in Laravel

How to Get Current Date Time and Format in Laravel ?

September 2, 2022March 16, 2024

Laravel has carbon library to get the current date time and format in laravel and also we can use core php date functions to fetch the date and time. After php 5, php also introduced DateTime class to conduct the operations of date time related functionality. Sometimes in our application…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
  • Building a Million-Dollar Brand: The Journey of Justin Jackson
  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version