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

How to use if else condition in Laravel 8 blade file ?

December 17, 2021January 18, 2022

In this tutorial i will show you to use if else, if and else if in Laravel blade. Laravel use blade engine to render the template and blade have rich features to use conditional statements in file. So here i will show you to use @if, @elseif and @else in…

Read More
Php Laravel hasMany

How to Use hasMany Relationship in Laravel with Example ?

February 27, 2022November 10, 2023

Laravel hasMany relationship is used to create the relation between two tables. hasMany means create the relation one to Many. For example if a article have comments and we wanted to get all comments of the article then we can use hasMany relationship . Database Relations are used to create…

Read More

Create Custom Class or Custom Library in Laravel 10

March 14, 2023March 16, 2024

In Laravel, you can create custom classes or custom library in laravel that can be used throughout your application. These classes can be used to encapsulate common functionality, business logic, or to abstract away complex operations. Thus I this article i will show you to create a class and use…

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

  • 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

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version