Burada, Laravel 10'u kuracağız ve çoklu resim seçimi için bir dosya giriş alanına sahip basit bir form oluşturacağız. Formu gönderdikten sonra bu resimleri bir klasöre ve veritabanına kaydedeceğiz.
Laravel 10 uygulamasında çoklu resim yükleme örneğini oluşturmak için aşağıdaki adımları izleyelim.
Adım 1: Laravel 10 Kurulumu
Bu adım zorunlu değildir; ancak, Laravel uygulamanızı henüz oluşturmadıysanız, aşağıdaki komutu çalıştırabilirsiniz:
composer create-project laravel/laravel example-app
Adım 2: Migration ve Model Oluşturma
Burada, "images" tablosu için migration oluşturacağız. Aşağıdaki komutu çalıştırarak migration'ı oluşturalım ve kodu güncelleyelim.
php artisan make:migration create_images_table
database/migrations/2022_02_10_140040_create_images_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
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');
}
};
Sonraki adımda, aşağıdaki Laravel migration komutunu kullanarak yeni bir migration oluşturun:
php artisan migrate
Şimdi Image modelini oluşturmak için aşağıdaki komutu kullanacağız:
php artisan make:model Image
app/Models/Image.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
}
Adım 3: Controller Oluşturma
Bu adımda, ImageController adında yeni bir controller oluşturacağız. Bu controller içerisinde index() ve store() olmak üzere iki yöntem bulunacak. index() yöntemi, görünümü render etmekten sorumlu olacak, store() yöntemi ise resimleri klasöre ve veritabanına kaydetme mantığını işleyecektir.
ImageController'ı oluşturmak için aşağıdaki komutu çalıştırın:
php artisan make:controller ImageController
app/Http/Controllers/ImageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
class ImageController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(): View
{
return view('imageUpload');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request): RedirectResponse
{
$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);
}
}
Adım 4: Rotaları Oluşturma ve Eklemek
Ayrıca, routes/web.php dosyasını açın ve görünümü render etmek ve resim kaydetme mantığını yönetmek için GET ve POST isteklerini yönlendirecek rotaları ekleyin.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::controller(ImageController::class)->group(function(){
Route::get('image-upload', 'index');
Route::post('image-upload', 'store')->name('image.store');
});
Adım 5: Blade Dosyası Oluşturma
Son adımda, imageUpload.blade.php adlı bir Blade dosyası oluşturmanız gerekmektedir. Bu dosyada, bir dosya giriş butonu ile bir form oluşturacağız. Aşağıdaki kodu kopyalayın ve bu dosyaya yapıştırın.
resources/views/imageUpload.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 Multiple 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 Multiple Image Upload Example</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>
</html>
Laravel Uygulamasını Çalıştırma:
Gerekli adımlar tamamlandıktan sonra, aşağıdaki komutu yazın ve Enter tuşuna basarak Laravel uygulamasını çalıştırın:
php artisan serve
Daha sonra web tarayıcınıza gidin, verilen URL'yi yazın ve uygulamanın çıktısını görüntüleyin:
http://localhost:8000/image-upload
Bu adımları takip ederek, Laravel uygulamanızı çalıştırabilir ve resim yükleme formunu görüntüleyebilirsiniz.
