Upload Image

Untuk membuat fungsi upload image, kita harus membuat link storage dulu di aplikasi laravel kita. Sekarang buka terminal dan jalankan perintah berikut.

php artisan storage:link

Kemudian tekan enter.

Lebih lengkapnya bisa dibaca di dokumentasinya (https://laravel.com/docs/5.8/filesystem#introduction)

# Setting

Agar bisa berjalan dengan sepenuhnya, kita perlu melakukan beberapa setting.

 .env

Buka file .env kemudian cari bagian APP_URL, ubah nilainya menjadi seperti berikut.

APP_URL=http://localhost:8000

filesystems.php

Buka file filesystems.php di dalam folder config, kemudian ubah bagian default menjadi 'public'

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */

    'default' => env('FILESYSTEM_DRIVER', 'public'),

    /*
    |--------------------------------------------------------------------------
    | Default Cloud Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Many applications store files both locally and in the cloud. For this
    | reason, you may specify a default "cloud" driver here. This driver
    | will be bound as the Cloud disk implementation in the container.
    |
    */

    'cloud' => env('FILESYSTEM_CLOUD', 's3'),

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    | Supported Drivers: "local", "ftp", "sftp", "s3", "rackspace"
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],

    ],

];

# ImageController

Kembali ke terminal lagi dan buat file ImageController.php dengan mengetik perintah berikut.

php artisan make:controller ImageController

kemudian tekan enter.

Buka file ImageController.php dan isi dengan skrip berikut.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Image;

class ImageController extends Controller
{
    public function index(Request $request) {
        $itemuser = $request->user();
        $itemgambar = Image::where('user_id', $itemuser->id)->paginate(20);
        $data = array('title' => 'Data Image',
                    'itemgambar' => $itemgambar);
        return view('image.index', $data)->with('no', ($request->input('page', 1) - 1) * 20);
    }
    public function store(Request $request)
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
        $itemuser = $request->user();
        $fileupload = $request->file('image');
        $folder = 'assets/images';
        $itemgambar = $this->upload($fileupload, $itemuser, $folder);
        // $inputan = $request->all();
        // $inputan['user_id'] = $itemuser->id;
        // Image::create($inputan);
        return back()->with('success', 'Image berhasil diupload');
    }

    public function destroy(Request $request, $id) {
        $itemuser = $request->user();
        $itemgambar = Image::where('user_id', $itemuser->id)
                            ->where('id', $id)
                            ->first();
        if ($itemgambar) {
            \Storage::delete($itemgambar->url);
            $itemgambar->delete();
            return back()->with('success', 'Data berhasil dihapus');
        } else {
            return back()->with('error', 'Data tidak ditemukan');
        }
    }
    
    public function upload($fileupload, $itemuser, $folder) {
        $path = $fileupload->store('files');
        $inputangambar['url'] = $path;
        $inputangambar['user_id'] = $itemuser->id;
        return Image::create($inputangambar);
    }
}

# views image

Setelah controller selesai kita buat, selanjutnya buat 1 buah folder dengan nama image di dalam views. Kemudian di dalam folder image buat 1 buah file dengan nama index.blade.php dan isi dengan skrip berikut.

@extends('layouts.dashboard')
@section('content')
<div class="container-fluid">
  <div class="row">
    <div class="col">
      <div class="card">
        <div class="card-header">
          <h3 class="card-title">Image</h3>
        </div>
        <div class="card-body">
          <form action="{{ url('/admin/image') }}" method="post" enctype="multipart/form-data" class="form-inline">
          @csrf
          <div class="form-group">
            <input type="file" name="image" id="image">
          </div>
          <div class="form-group">
            <button class="btn btn-primary">Upload</button>
          </div>
          </form>
        </div>
        <div class="card-body">
          @if(count($errors) > 0)
          @foreach($errors->all() as $error)
              <div class="alert alert-warning">{{ $error }}</div>
          @endforeach
          @endif
          @if ($message = Session::get('error'))
              <div class="alert alert-warning">
                  <p>{{ $message }}</p>
              </div>
          @endif
          @if ($message = Session::get('success'))
              <div class="alert alert-success">
                  <p>{{ $message }}</p>
              </div>
          @endif
          <div class="row">
            @foreach($itemgambar as $gambar)
            <div class="col col-lg-3 col-md-3 mb-2">
              <img src="{{ \Storage::url($gambar->url) }}" alt="img" class="img-thumbnail mb-2">
              <form action="{{ url('/admin/image/'.$gambar->id) }}" method="post" style="display:inline;">
                @csrf
                {{ method_field('delete') }}
                <button type="submit" class="btn btn-sm btn-danger mb-2">
                  Hapus
                </button>                    
              </form>
            </div>
            @endforeach
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection

# route

Kita perlu menambahkan beberapa route di file web.php untuk fungsi upload image.

<?php

/*
|--------------------------------------------------------------------------
| 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::get('/', '[email protected]');
Route::get('/about', '[email protected]');
Route::get('/kontak', '[email protected]');
Route::get('/kategori', '[email protected]');
Route::get('/kategori/{slug}', '[email protected]');
Route::get('/produk', '[email protected]');
Route::get('/produk/{slug}', '[email protected]');

Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function() {
  Route::get('/', '[email protected]');
  // route kategori
  Route::resource('kategori', 'KategoriController');
  // route produk
  Route::resource('produk', 'ProdukController');
  // route customer
  Route::resource('customer', 'CustomerController');
  // route transaksi
  Route::resource('transaksi', 'TransaksiController');
  // profil
  Route::get('profil', '[email protected]');
  // setting profil
  Route::get('setting', '[email protected]');
  // form laporan
  Route::get('laporan', '[email protected]');
  // proses laporan
  Route::get('proseslaporan', '[email protected]');
  // image
  Route::get('image', '[email protected]');
  // simpan image
  Route::post('image', '[email protected]');
  // hapus image by id
  Route::delete('image/{id}', '[email protected]');
});

Auth::routes();

Route::get('/home', '[email protected]')->name('home');

# Trial

Karena kita tidak menambahkan menu upload image di menu dashboard, maka sekarang jalankan aplikasi kita kemudian akses halaman http://localhost:8000/admin/image

Coba upload beberapa gambar dan hapus lagi. Pastikan tidak ada error.

Setelah diupload 2 gambar. Selamat mencoba

Pada tutorial selanjutnya kita akan menambahkan fungsi upload gambar kategori.

 

Mau Bikin Aplikasi Web & Aplikasi Android?

Saya membuka jasa pembuatan aplikasi web dan android untuk aplikasi seperti toko online, monitoring (IoT), interface mesin absensi atau kasir

Silahkan kontak link di bawah ini untuk teknis dan harganya