Laravel 9 - Membuat Multiple Image Upload

Hallo, pada postingan kali ini saya akan memberikan contoh bagaimana membuat Multiple  upload file di Laravel 9 , disini saya akan menjelaskan cara sederhana dan Langkah demi Langkah untuk membuat code multiple upload file di Laravel 9 tentunya.

Pada tutorial sebelumnya saya juga pernah membahas bagaimana membuat upload file di laravel 9

Silahkan Ikuti Langkah Langkah Berikut :

1. Langkah Pertama install laravel

composer create-project laravel/laravel example-app

 

2, Buat migration dan model

php artisan make:migration create_images_table

kemudian cek pada folder : database/migrations/2022_05_10_140040_create_images_table.php

<?php
use IlluminateDatabaseMigrationsMigration;

use IlluminateDatabaseSchemaBlueprint;

use IlluminateSupportFacadesSchema;
return new class extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::create('images', function (Blueprint $table) {

            $table->id();

            $table->string('name');

            $table->timestamps();

        });

    }

  

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('images');

    }

};

 

selanjutnya lakukan migration dengan cara buat perintah pada command line:

php artisan migrate

3. Langkah Selanjutnya Silahkan Buat Sebuah Model

php artisan make:model Image

app/Models/Image.php

Silahkan Ketikan script Berikut :

<?php

namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;

use IlluminateDatabaseEloquentModel;

class Image extends Model

{

    use HasFactory;
    protected $fillable = [

        'name'

    ];

}

 

4. Buat Sebuah Controller

silahkan ketikan perintah berikut pada commad line anda

php artisan make:controller ImageController

kemudian silahkan cek pada app/Http/Controllers/ImageController.php kemudian masukan script berikut :

<?php

namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsImage;


class ImageController extends Controller
{

    public function index()

    {

        return view('imageUpload');

    }
    public function store(Request $request)
    {

        $request->validate([

            'images' => 'required',

            'images.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',

        ]);


        $images = [];

        if ($request->images){

            foreach($request->images as $key => $image)

            {

                $imageName = time().rand(1,99).'.'.$image->extension();  

                $image->move(public_path('images'), $imageName);

  

                $images[]['name'] = $imageName;

            }

        }

        foreach ($images as $key => $image) {

            Image::create($image);

        }

        return back()

                ->with('success','You have successfully upload image.')

                ->with('images', $images); 

    }

}

 

5. Tambahkan Routes

Silahkan Tambahkan Routes pada routes/web.php

 

<?php

use IlluminateSupportFacadesRoute;
use AppHttpControllersImageController;
Route::controller(ImageController::class)->group(function(){

    Route::get('image-upload', 'index');

    Route::post('image-upload', 'store')->name('image.store');

});

 

6. Langkah Selanjutnya kita buat view nya

resources/views/imageUpload.blade.php

 

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Multiple Image </title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

</head>

<body>
<div class="container">
    <div class="panel panel-primary">
      <div class="panel-heading">
        <h2>Laravel 9 Multiple Image Upload</h2>
      </div>
      <div class="panel-body">

        @if ($message = Session::get('success'))

            <div class="alert alert-success alert-dismissible fade show" role="alert">

              <strong>{{ $message }}</strong>

              <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>

            </div>

            @foreach(Session::get('images') as $image)

                <img src="images/{{ $image['name'] }}" width="300px">

            @endforeach

        @endif

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

            @csrf

            <div class="mb-3">

                <label class="form-label" for="inputImage">Select Images:</label>

                <input 

                    type="file" 

                    name="images[]" 

                    id="inputImage"

                    multiple 

                    class="form-control @error('images') is-invalid @enderror">

  

                @error('images')

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

 

Silahakan Jalan kan Aplikasi.. Selamat Mencoba.

 

 

 

image

Mazadie

Assalamualikum .. Saya adalah Seorang Web Developer Asal Riau.

Komentar