Bu örnekte size Laravel 10 çoklu dosya yükleme örneğini göstereceğim.
İşte Laravel 10 uygulamasında birden fazla dosya yüklemek için aşağıdaki adımları izleyelim.
Adım 1: Laravel 10'ı Kurun
Bu adım gerekli değildir, ancak eğer Laravel uygulamanı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, "files" tablosu için bir migration oluşturacağız, aşağıdaki komutu çalıştırarak kodu güncelleyelim.
php artisan make:migration create_files_table
database/migrations/2022_02_11_032608_create_files_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('files', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('files');
}
};
Ardından, aşağıdaki komutu çalıştırın:
php artisan migrate
Şimdi, aşağıdaki komutu kullanarak File modelini oluşturacağız:
php artisan make:model File
app/Models/File.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
}
Adım 3: Controller Oluşturma
Bu adımda, yeni bir FileController oluşturacağız. Bu dosyada, görünümü render etmek ve dosyaları klasöre ve veritabanına kaydetmek için index() ve store() adında iki metod ekleyeceğiz.
Aşağıdaki komutu kullanarak FileController'ı oluşturalım:
php artisan make:controller FileController
Daha sonra, Controller dosyasını aşağıdaki kodla güncelleyelim.
app/Http/Controllers/FileController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
class FileController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(): View
{
return view('fileUpload');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'files' => 'required',
'files.*' => 'required|mimes:pdf,xlx,csv|max:2048',
]);
$files = [];
if ($request->file('files')){
foreach($request->file('files') as $key => $file)
{
$fileName = time().rand(1,99).'.'.$file->extension();
$file->move(public_path('uploads'), $fileName);
$files[]['name'] = $fileName;
}
}
foreach ($files as $key => $file) {
File::create($file);
}
return back()
->with('success','You have successfully upload file.');
}
}
Adım 4: Rotaları Oluşturma ve Eklemek
routes/web.php dosyasını açın ve görünümü render etmek ve dosyaları kaydetmek için GET ve POST isteklerini yönetmek için rotaları ekleyin.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileController;
/*
|--------------------------------------------------------------------------
| 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(FileController::class)->group(function(){
Route::get('file-upload', 'index');
Route::post('file-upload', 'store')->name('file.store');
});
Adım 5: Blade Dosyası Oluşturma
Son adımda, fileUpload.blade.php adında bir blade dosyası oluşturmanız gerekiyor. Bu dosyada, bir form ve dosya seçme butonu oluşturacağız. Aşağıdaki kodu kopyalayın ve fileUpload.blade.php dosyasına yapıştırın.
resources/views/fileUpload.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 Multiple File 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 File Upload Example</h2>
</div>
<div class="panel-body">
@if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<strong>{{ $message }}</strong>
</div>
@endif
<form action="{{ route('file.store') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="mb-3">
<label class="form-label" for="inputFile">Select Files:</label>
<input
type="file"
name="files[]"
id="inputFile"
multiple
class="form-control @error('files') is-invalid @enderror">
@error('files')
<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 ve aşağıdaki URL'yi yazarak uygulama çıktısını görüntüleyin:
