Surfe.be - passive income

How to upload Multiple Image in Laravel

How to upload multiple image

Today, i will show you how to create simple multiple image upload in laravel. I write article step by step about multiple image upload in laravel. I also added validation with image upload in laravel. Here i will follow object oriented php structure to upload imgae. It is very easy and preety awesome . Here i also validate image where user can only upload jpeg,png,jpg,gif type image. So doing it you can download a fresh laravel file or you can do it in your current running project. So just follow few steps. Here i will use a fresh laravel app .

Laravel Multiple Image Upload

Now follow step by step. It is very easy and simple. You can also upload file using this code not only image. So you can use this procedure to upload image or file. Let’s start.

Upload Multiple Image/File

Step 1 : Install Laravel  App

To do it run bellow command in your project directory.

composer create-project --prefer-dist laravel/laravel imageUpload

After running this command create our migration

Step 2 : Create migration

For creating migration run bellow command

php  artisan make:model Image -m -r

Then go to migration table database/migrations/images.php and paste the following code.

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

class CreateImageTable extends Migration
{
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('image');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Then connect your database and migrate your database using below command.

php artisan migrate

Now goto your Image model and paste this following code.

namespace App;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{   
	protected $guarded = [];
   
}

Now our database is ready . Now create route

Step 3 : Setup Route

go to your routes/web.php and paste the following code

Route::resource('image','ImageController');

Now we have to create a trait. If you don’t know what is trait in php then please read this article before.

What is Traits in PHP ?

Here we want to create a trait because , if you upload a image using trait then you can use this trait method any where to upload file. Just you have to use this trait in your controller . That’s it. It’s awesome i think.

Step 4: Create a Trait

Go to your app folder and create a folder name Traits and whose namespace will be App/Traits/ImageUpload.php . Create it manually , not using command line .Now paste this following code to your traits file.

namespace App\Traits;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

trait ImageUpload
{
    public function UserImageUpload($query) // Taking input image as parameter
    {
        $image_name = str_random(20);
        $ext = strtolower($query->getClientOriginalExtension()); // You can use also getClientOriginalName()
        $image_full_name = $image_name.'.'.$ext;
        $upload_path = 'image/';    //Creating Sub directory in Public folder to put image
        $image_url = $upload_path.$image_full_name;
        $success = $query->move($upload_path,$image_full_name);

        return $image_url; // Just return image
    }
}

Step 5: Setup ImageController

Now go to your ImageController and paste those following code.

namespace App\Http\Controllers\ImageController

use App\Http\Controllers\Controller;
use App\Image;
use App\Traits\ImageUpload;
use Illuminate\Http\Request;

class ImageController extends Controller{

       use ImageUpload; //Using our created Trait to access inside trait method

       $request->validate([
          'image' => 'required'
        ]);
         
        if ($request->hasFile('image')) {
        foreach($request->file('image ') as $file){
     
          $filePath = $this->UserImageUpload($file); //passing parameter to our trait method one after another using foreach loop
          
            Image::create([
              'name' => $filePath,
            ]);
          }
 
         Toastr::success('Image uploaded successfully :)','Success');
        }

        return redirect()->back();
}

Hope you will understand all the procedures.

Step 6 : Create our blade file

For creating blade file just paste this following code

<form action="{{ route('image.store') }}" method="post" enctype="multipart/form-data">
    @csrf

<input type="file" name="image[]" required="" multiple >
<input type="submit" value="submit">

</form>

Step 7 : Retrive Image from database

Now just retrive your image from your controller and print it like below using a foreach loop. Hope you will get it.

<img src="/{{ $YourVariableName->image }}" style="height: 70px; width: 70px; border-radius: 50%;">

That’s it. Hope you will enjoy this tutorial . If you like this tutorial , please share and don’t forget to share your experience. If you wanna learn more about file upload then you can visit here and read thid documentation.

Leave a comments

LET'S SOCIALITE

Recent Tweets