Getting Started with Cloudflare R2

Getting Started with Cloudflare R2

Langkah 4: Model, View, dan Controller

Kita buat ketiganya dalam satu perintah.

php artisan make:model Storage -mcr
   INFO  Model [app/Models/Storage.php] created successfully.  

   INFO  Migration [database/migrations/2025_01_04_005141_create_storages_table.php] created successfully.  

   INFO  Controller [app/Http/Controllers/StorageController.php] created successfully. 

Dengan perintah di atas, kita membuat model Storage sekaligus migration dan resource controller.


Untuk migration, kita buat sederhana dulu saja seperti ini:

<?php

// ...

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('storages', function (Blueprint $table) {
            $table->id();
            $table->string('path');
            $table->timestamps();
        });
    }

    // ...
}

Jalankan migratenya

php artisan migrate

File migration di atas setara dengan SQL command berikut:

create table "storages" (
    "id" integer primary key autoincrement not null, 
    "path" varchar not null, 
    "created_at" datetime, 
    "updated_at" datetime
);

Selanjutnya kita modifikasi file controllernya seperti ini:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class StorageController extends Controller
{
    public function index()
    {
        return view('upload');
    }

    public function store(Request $request)
    {
        try {
            $path = $request->file('file')->store('storage');

            $storage = new \App\Models\Storage();
            $storage->path = $path;
            $storage->save();
        } catch (\Throwable $th) {
            dd($th->getMessage());
        }

        return back();
    }
}

Pada method index, kita sesederhana menampilkan view yang nanti berada di resources/views/upload.blade.php dan isinya berupa form upload saja dengan 2 elemen, yakni element input file dan tombol.

Adapun pada method store, hanya berupa usaha untuk upload file ke Cloudflare R2 dan menyimpannya ke dalam model Storage. Jika gagal, maka akan menampilkan errornya dalam fungsi dd. Jika berhasil, maka kembali ke halaman upload lagi.

Kita hanya menggunakan dua method itu saja dan silahkan hapus method lainnya karena tidak diperlukan.


Terakhir, buat file baru dengan nama upload.blade.php dalam folder resources/views dan isinya sesederhana berikut:

<!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>Upload to Cloudflare R2</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
</head>

<body class="container">

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

        <input type="file" name="file" id="file" required>

        <input type="submit" value="Upload">
    </form>

</body>

</html>

Ups, sebelum kita coba di browser, kita harus menambahkan route juga di routes/web.php seperti ini:

<?php

// ...

Route::resource('storage', \App\Http\Controllers\StorageController::class)
    ->only(['index', 'store']);

Nah, saatnya pembuktian di browser!

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *