Loading image

Blogs /

Simplify Image Uploads: Creating a Generic Image Function in Laravel 10

Simplify Image Uploads: Creating a Generic Image Function in Laravel 10

  • showkat ali
  • 0 Comments
  • 864 View

In this tutorial, I will walk you through a Laravel 10 image upload example. We will explore the process of uploading images in a Laravel 10 application. This example is designed to guide you on how to upload images to the database using Laravel 10. We'll go into detail on how to upload and display images in a Laravel 10 project.

Throughout this tutorial, we will create two routes – one for the GET method and another for the POST method. We'll set up a straightforward form with a file input field, making it easy for users to select an image. The chosen image will be uploaded to the 'images' directory within the public folder of your Laravel project. So, follow along with the steps below to learn how to effortlessly implement image uploads in your Laravel 10 application.

 

See the preview of this tutorial on how to upload and display images in Laravel 10:

 

Step 1: Download Fresh Laravel

In this first step, we need a fresh Laravel 10 application for the laravel 10 image upload and display. So download it by the below command:

composer create-project laravel/laravel example-app

We are going to use the User model. Now update by adding an image uploading system which means an image column to the users table like below:

 

Step 2: Make Model / Migration /Controller

php artisan make:model Post -mc

database/migrations

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('image_name')->nullable();
            $table->string('image_type')->nullable();
            $table->string('image_size')->nullable();
            $table->string('image_path')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

And now update the model like:

app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title','image_name','image_type','image_size','image_path'];
}

Step 3: Connect database

After successfully installing the laravel app and then configuring the database setup. We will open the ".env" file and change the database name, username, and password in the env file to create an image upload in laravel 10.

.env

 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

 

Now run php artisan migrate command to update the database. 

php artisan migrate

 Step 4:  Create Route

Now in this, create a resource route like the one below to complete the image upload function in laravel I am going to use a resource controller. So define the resource route like the below:

routes/web.php

Route::get('/', 'PostController@index');
Route::post('post/store', 'PostController@store')->name('post.store');

 Step 5: Create Controller

Now in this step, we have to already created a PostController  to define this method to create a laravel image upload example.

Now, open the PostController.php file and include the necessary code for handling the image upload process:

 

 

app/Http/Controllers/PostController.php

 

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Traits\ImageUpload;
use Illuminate\Http\Request;

class PostController extends Controller
{
    use ImageUpload;
    public function store(Request $request)
    {
        $data = $request->all();
        $path = "user/profile/";
        if ($file = $request->file('image')) {
            $fileData = $this->uploads($file, $path);
            $data['image_path'] = $fileData['filePath'];
            $data['image_size'] = $fileData['fileSize'];
            $data['image_type'] = $fileData['fileType'];
            $data['image_name'] = $fileData['fileName'];
        }

        Post::create($data);
        return back()->with('success', 'Successfully Store Image');
    }
    public function update(Request $request)
    {

        $existingPhoto = Post::find($id)->photo;
        $userPhotoPath = "user/profile/";
        if ($file = $request->file('photo')) {
            $fileData = $this->uploads($file, $userPhotoPath, $existingPhoto);
            $data['photo'] = $fileData['filePath'];
        }
    }
}

In this controller, we have used the ImageUpload trait to handle the image upload process. It extracts the image file from the request, saves it to the specified path, and stores relevant information in the database.

 

Step 6: Creating the "ImageUpload" Trait

To make this approach work, you need the "ImageUpload" trait. This trait streamlines the image upload process and encapsulates the logic for reuse in different parts of your application. Here is the "ImageUpload" trait:

<?php

namespace App\Traits;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;


trait ImageUpload
{

    public function uploads($file, $path, $existingFile = null)
    {
        if ($existingFile) {
            Storage::disk('public')->delete($existingFile);
        }
        if ($file && $file->isValid()) {
            $unqRan = Str::random(20);
            $fileName = time() . $unqRan . $file->getClientOriginalName();
            Storage::disk('public')->putFileAs($path, $file, $fileName);
            $file_name = $file->getClientOriginalName();
            $file_type = $file->getClientOriginalExtension();
            $filePath = $path . $fileName;

            return [
                'fileName' => $file_name,
                'fileType' => $file_type,
                'filePath' => $filePath,
                'fileSize' => $this->fileSize($file)
            ];
        }

        return null;
    }

    public function fileSize($file, $precision = 2)
    {
        $size = $file->getSize();

        if ($size > 0) {
            $size = (int) $size;
            $base = log($size) / log(1024);
            $suffixes = array(' bytes', ' KB', ' MB', ' GB', ' TB');
            return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
        }

        return $size;
    }
}

This trait consists of two main functions:

  1. uploads($file, $path, $existingFile = null): This function manages the upload of image files. It also allows you to replace an existing file if necessary and returns valuable information about the uploaded file.

  2. fileSize($file, $precision = 2): This auxiliary function helps calculate the file size in a human-readable format, such as KB, MB, GB, etc.

 

Step 7: 

Creating the Blade View

In your Laravel project, create a Blade view that allows users to upload images. Here's a sample Blade view that you can use:

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>how to add image in laravel 10</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</head>

<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3>How to make Generic Method to add image in laravel 10</h3>
                    </div>
                    <div class="card-body">
                        <form action="{{ route('post.store') }}" method="post" enctype="multipart/form-data">
                            @csrf
                            <div class="form-group">
                                <label for="exampleFormControlFile1">Title</label>
                                <input class="form-control" type="text" name="title" placeholder="Enter Title">

                            </div>
                            <div class="form-group">
                                <label for="exampleFormControlFile1">image</label>
                                <input type="file" name="image" class="form-control-file"
                                    id="exampleFormControlFile1">
                            </div>
                            <button type="submit" class="btn btn-primary float-right">Submit</button>

                        </form>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-8">
                <div class="card mb-5">
                    <div class="card-header">
                        <h3>List</h3>
                    </div>
                    <div class="card-body">

                        <table class="table">
                            <thead class="thead-dark">
                                <tr>
                                    <th scope="col">#</th>
                                    <th scope="col">Title</th>
                                    <th scope="col">Image </th>
                                    <th scope="col">Type</th>
                                    <th scope="col">Image Name</th>
                                    <th scope="col">Size</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($posts as $post)
                                    <tr>
                                        <th scope="row">{{$post->id}}</th>
                                        <td>{{$post->title}}</td>
                                        <td><img src="{{Storage::url($post->image_path)}}" alt="" width="100" height="100"></td>
                                        <td>{{$post->image_type}}</td>
                                        <td>{{$post->image_name}}</td>
                                        <td>{{$post->image_size}}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>

                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

Now all are set to go. Now run php artisan serve command to start the development server and visit the following URL to check this laravel image upload tutorial. Don't forget to run this command php artisan storage:link and then visit:

 

Conclusion:

In this tutorial, we've explored how to simplify image uploads in Laravel 10 by creating a generic "ImageUpload" function. This approach allows you to handle image uploads consistently and efficiently across your Laravel projects, promoting code reusability and maintainability.

By implementing a generic image upload method, you can streamline your development process, ensure consistency in your code, and provide a user-friendly experience for your application's users. Whether it's user avatars, product images, or any other type of media, this approach makes handling image uploads in Laravel a breeze.

 

showkat ali Author

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur based in Pakistan. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance

0 Comments

Post Comment

Recent Blogs

Recent posts form our Blog

How to Deploy a Next.js Application on AWS EC2 Using GitHub Actions

How to Deploy a Next.js Application on AWS EC2 Using GitHub Actions

showkat ali
/
Programming

Read More
How To Integrate Paypal Payment Gateway In Laravel 10

How To Integrate Paypal Payment Gateway In Laravel 10

showkat ali
/
Programming

Read More
A Step-by-Step Guide:How to integrate stripe payment into laravel 10

A Step-by-Step Guide:How to integrate stripe payment into laravel 10

showkat ali
/
Programming

Read More
How to Create a Custom Signup Form in Django 5.0

How to Create a Custom Signup Form in Django 5.0

Qadir Hassan
/
Programming

Read More
how to Integrate Stripe recurring payment into Laravel [2024]

how to Integrate Stripe recurring payment into Laravel [2024]

showkat ali
/
Programming

Read More
Character AI: An Overview and How It Could Affect the World

Character AI: An Overview and How It Could Affect the World

showkat ali
/
Programming

Read More