[COMMON] Image Upload, File upload, Multiple Image,Files, filesystems, Route::controller full (ok)

https://www.itsolutionstuff.com/post/laravel-9-image-upload-example-tutorialexample.html

Chú ý: Chúng ta không sử dụng đồng thời hai kiểu upload như: $request->file->move, $request->file->storeAs vì nếu sử dụng đồng thời chúng sẽ báo lỗi :) fopen(): Filename cannot be empty

https://www.itsolutionstuff.com/post/laravel-9-file-upload-tutorial-exampleexample.html

Ví dụ 0: Upload ảnh từ input bằng js

C:\xampp\htdocs\laravelvue\config\filesystems.php

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

C:\xampp\htdocs\laravelvue\app\Http\Controllers\CustomerController.php

public function store(Request $request) {
  // ...
if($request->image_customer) {
  $image = $request->image_customer;
  $name = time() . "_" . $image->getClientOriginalName();
  Storage::disk('public')->put($name,File::get($image));
  $customer->image_customer = $name;
}else {
  $customer->image_customer = 'default.png';
}
  // ...
  $customer->save();
}

C:\xampp\htdocs\laravelvue\resources\js\components\CustomerComponent.vue

<template>
    <div class="container">
        <div class="row my-5">
            <div class="col-md-12 border mt-2 py-3">
                <button type="button" class="btn btn-primary mt-2" @click="showAdd">Add</button>
            </div>
            <div class="col-md-12 border mt-2 py-3" v-if="display">
                <form @submit.prevent="addCustomer" enctype="multipart/form-data">
                    <div class="form-floating mb-3">
                        <input type="file" class="form-control-file" id="image">
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" placeholder="Name Customer" v-model="customer.name_customer">
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" placeholder="Phone Customer" v-model="customer.phone_customer">
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" placeholder="Address Customer" v-model="customer.address_customer">
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" placeholder="Email Customer" v-model="customer.email_customer">
                    </div>
                    <div class="form-floating mb-3">
                        <input type="text" class="form-control" placeholder="City Customer" v-model="customer.city_customer">
                    </div>
                    <button type="submit" class="btn btn-warning mt-2">Save</button>
                </form>
            </div>
            <div class="col-md-12 border mt-2 py-3">
                <nav aria-label="Page navigation example">
                    <ul class="pagination">
                        <li class="page-item"><a class="page-link" @click="fetchData(pagination.first)" href="#">First</a></li>
                        <li class="page-item"><a class="page-link" @click="fetchData(pagination.prev)"  :class="[{disabled: !pagination.prev}]" href="#">Previous</a></li>
                        <li class="page-item"><a class="page-link" @click="fetchData(pagination.next)" :class="[{disabled: !pagination.next}]" href="#">Next</a></li>
                        <li class="page-item"><a class="page-link" href="#">{{ pagination.current_page }}</a></li>
                        <li class="page-item"><a class="page-link">...</a></li>
                        <li class="page-item"><a class="page-link" href="#">{{ pagination.last_page }}</a></li>
                        <li class="page-item"><a class="page-link" @click="fetchData(pagination.last)" href="#">Last</a></li>
                    </ul>
                </nav>
            </div>
            <div class="col-md-12 border mt-2 py-3" v-for="(customer, index) in customers" v-bind:key="index">
                <p>Address: {{ customer.address_customer }}</p>
                <p><img style=" width: 100px; " :src="'public/images/'+customer.image_customer" alt="Image"></p>
                <p>City: {{ customer.city_customer }}</p>
                <p>Email: {{ customer.email_customer }}</p>
                <p>Name: {{ customer.name_customer }}</p>
                <div>Phone: {{ customer.phone_customer }}</div>
                <button type="button" class="btn btn-warning mt-2" @click="deleteCustomer(customer.id_customer)">Delete</button>
                <button type="button" class="btn btn-secondary mt-2" @click="editCustomer(customer)">Edit</button>
            </div>
        </div>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                customers: [],
                pagination: {},
                customer: {
                    'image_customer': '',
                    'name_customer': '',
                    'phone_customer': '',
                    'address_customer': '',
                    'email_customer': '',
                    'city_customer': ''
                },
                edit: false,
                display: false
            }
        },
        created() {
            this.fetchData();
        },
        methods: {
            fetchData: function(page_url) {
                let vm = this;
                page_url = page_url || 'api/customers';
                fetch(page_url)
                .then(res => res.json())
                .then(res => {
                    this.customers = res.data;
                    vm.makePagination(res.meta,res.links)
                })
            },
            makePagination(meta,links) {
                let pagination = {
                    current_page: meta.current_page,
                    last_page: meta.last_page,
                    next: links.next,
                    prev: links.prev,
                    first: links.first,
                    last: links.last
                }
                this.pagination = pagination;
            },
            deleteCustomer(id) {
                if(confirm("Are you sure you want to delete")) {
                    fetch('http://localhost/laravelvue/api/customers/' + id, {
                        method: 'DELETE',
                    })
                    .then(res => res.text())
                    .then(res => this.fetchData())
                }
            },
            addCustomer() {
                if(this.edit === false) {
                    this.display = false;
                    let formData = new FormData();
                    formData.append('name_customer',this.customer.name_customer);
                    formData.append('phone_customer',this.customer.phone_customer);
                    formData.append('address_customer',this.customer.address_customer);
                    formData.append('email_customer',this.customer.email_customer);
                    formData.append('city_customer',this.customer.city_customer);
                    if(document.getElementById('image').files[0]){
                        formData.append('image_customer',document.getElementById('image').files[0]);
                    }
                    fetch('http://localhost/laravelvue/api/customers', {
                        method: 'POST',
                        body: formData
                    }).then(res => res.text())
                    .then(
                        res => {
                            this.display = false;
                            this.fetchData()
                        }
                    );
                }else {
                    fetch('http://localhost/laravelvue/api/customers/'+this.customer.id_customer, {
                        method: 'PUT',
                        body: JSON.stringify(this.customer),
                        headers: {
                            'content-type': 'application/json'
                        }
                    }).then(res => res.text())
                    .then(
                        res => {
                            this.display = false;
                            this.fetchData();
                        }
                    );
                }
            },
            editCustomer(customer) {
                this.edit = true;
                this.display = true;
                this.customer = customer;
            },
            showAdd() {
                this.display = true;
            }
        }
    }
</script>

Ví dụ 1: Thực hành với ảnh html

C:\xampp\htdocs\test\routes\web.php

<?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::get('/', function () {
  return view('welcome');
});
Route::controller(ImageController::class)->group(function () {
  Route::get('image-upload', 'index');
  Route::post('image-upload', 'store')->name('image.store');
});

C:\xampp\htdocs\test\resources\views\imageUpload.blade.php

<!DOCTYPE html>
<html>
	<head>
		<title>Laravel 9 Image Upload Example - ItSolutionStuff.com</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 9 Image Upload Example - ItSolutionStuff.com</h2>
				</div>
				<div class="panel-body"> 
					@if ($message = Session::get('success')) 
						<div class="alert alert-success alert-block">
							<button type="button" class="close" data-dismiss="alert">×</button>
							<strong>{{ $message }}</strong>
						</div>
						<img src="images/{{ Session::get('image') }}"> 
					@endif 
					<form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data"> 
						@csrf 
						<div class="mb-3">
							<label class="form-label" for="inputImage">Image:</label>
							<input type="file" name="image" id="inputImage" class="form-control @error('image') is-invalid @enderror"> 
							@error('image') 
								<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>

C:\xampp\htdocs\test\app\Http\Controllers\ImageController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ImageController extends Controller {
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index() {
    return view('imageUpload');
  }
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request) {
    $request->validate([
      'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);
    $imageName = time() . '.' . $request->image->extension(); // '1651654720.png'
    // 🤞 Store Image in Storage Folder
    $request->image->storeAs('images', $imageName);
    // storage/app/images/file.png
    // 🤞 Store Image in Public Folder
    $request->image->move(public_path('images'), $imageName);
    // public/images/file.png
    /* 
        Write Code Here for
        Store $imageName name in DATABASE from HERE 
    */
    return back()->with('success', 'You have successfully upload image.')->with('image', $imageName);
  }
}

Ví dụ 2: Thực hành với file pdf, .docx ...

C:\xampp\htdocs\test\routes\web.php

<?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::get('/', function () {
  return view('welcome');
});
Route::get('file-upload', [FileController::class, 'index']);
Route::post('file-upload', [FileController::class, 'store'])->name('file.store');

C:\xampp\htdocs\test\resources\views\fileUpload.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 9 File Upload Example - ItSolutionStuff.com</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 9 File Upload Example - ItSolutionStuff.com</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">File:</label>
          <input type="file" name="file" id="inputFile" class="form-control @error('file') is-invalid @enderror">
          @error('file')
            <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>

C:\xampp\htdocs\test\app\Http\Controllers\FileController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileController extends Controller {
  public function index() {
    return view('fileUpload');
  }
  public function store(Request $request) {
    $request->validate([
      'file' => 'required|mimes:pdf,xlx,csv,docx',
    ]);
    $fileName = time() . '.' . $request->file->extension();
    // storage/app/uploads/file.pdf
    // $request->file->move(public_path('uploads'), $fileName);
    $request->file->storeAs('uploads', $fileName);
    // public/uploads/file.docx
    /*
    Write Code Here for
    Store $fileName name in DATABASE from HERE
     */
    return back()->with('success', 'You have successfully upload file.')->with('file', $fileName);
  }
}

Kết quả:

Ví dụ 3: Multiple Image Upload

C:\xampp\htdocs\test\routes\web.php

<?php
use App\Http\Controllers\ImageController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
  return view('welcome');
});
Route::controller(ImageController::class)->group(function () {
  Route::get('image-upload', 'index');
  Route::post('image-upload', 'store')->name('image.store');
});

C:\xampp\htdocs\test\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',
  ];
}

C:\xampp\htdocs\test\app\Http\Controllers\ImageController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Image;
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);
  }
}

C:\xampp\htdocs\test\resources\views\imageUpload.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 9 Multiple Image Upload Example - ItSolutionStuff.com</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 9 Multiple Image Upload Example - ItSolutionStuff.com</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>

Ví dụ 4: Multiple File Upload

C:\xampp\htdocs\test\routes\web.php

<?php
use App\Http\Controllers\FileController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
  return view('welcome');
});
Route::controller(FileController::class)->group(function () {
  Route::get('file-upload', 'index');
  Route::post('file-upload', 'store')->name('file.store');
});

C:\xampp\htdocs\test\database\migrations\2022_05_04_171558_create_files_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFilesTable 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');
  }
}

C:\xampp\htdocs\test\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',
  ];
}

C:\xampp\htdocs\test\app\Http\Controllers\FileController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class FileController extends Controller {
  public function index() {
    return view('fileUpload');
  }
  public function store(Request $request) {
    $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.');
  }
}

C:\xampp\htdocs\test\resources\views\fileUpload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Multiple File Upload Example - ItSolutionStuff.com</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 9 Multiple File Upload Example - ItSolutionStuff.com</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>

Tìm hiểu về File Storage của Larave

Tìm hiểu về File Storage của Laravel

https://viblo.asia/p/tim-hieu-ve-file-storage-cua-laravel-gGJ59jBpKX2

Giới thiệu

  • Laravel cung cấp cho người dùng một giải pháp để quản lý file cực kỳ tiện lợi và hữu ích - đó là File Storage. Tính năng này bạn hoàn toàn có thể dùng trên các Framework khác vì nó là một package của Frank de Jonge. Bạn có thể xem package tại đây.

  • Với File Storage bạn có thể thao tác với các file ở local, Rackspace Cloud Storage và cả Amazon S3.

Config

  • Bạn có thể config File Storage tại file config/filesystems.php.

  • Driver mà Laravel hỗ trợ: "local", "ftp", "sftp", "s3", "rackspace".

Local

  • Để sử dụng và download các file trên web, bạn cần phải chạy lệnh sau để tạo ra một symbolic link trong thư mục public của Laravel: php artisan storage:link.

  • Mặc định, nó sẽ link đến đường dẫn storage/app/public. Bạn có thể config đường dẫn mà nó link đến tại dòng: 'root' => storage_path('app/public').

  • Để thao tác với thao trên web, bạn có thể dụng: asset('storage/filename');.

  • Để thao tác với file local, bạn có thể dùng Storage::disk('local')->put('file.txt', 'Contents');. Vì mặc định laravel sẽ dùng local nên bạn chỉ cần sử dụng Storage::put('file.txt', 'Contents');

S3 driver

Để lưu file lên Amazon S3 bạn cần install thêm package đó là:

Amazon S3: league/flysystem-aws-s3-v3 ~1.0`

Sau khi cài xong package, bạn cần config các thông số trong config/filesystems.php:

'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'),
],

FTP Driver

Bạn có thể sử dụng FTP Driver mà không cần thêm package giống như ở trên. Tuy nhiên, mặc định FTP sẽ không có sẵn trong config/filesystems.php. Để sử dụng FTP bạn phải thêm vào config/filesystems.php:

'ftp' => [
    'driver'   => 'ftp',
    'host'     => 'ftp.example.com',
    'username' => 'your-username',
    'password' => 'your-password',

    // Optional FTP Settings...
    // 'port'     => 21,
    // 'root'     => '',
    // 'passive'  => true,
    // 'ssl'      => true,
    // 'timeout'  => 30,
],

Thao tác với các disk

Như đã nói ở trên, mặc định ổ đĩa sẽ là local vì vậy nếu bạn muốn thao tác với Amazon S3 bạn sẽ cần sử dụng phương thức disk.

Mặc định:

Storage::put('avatars/1', $fileContents);

S3:

Storage::disk('s3')->put('avatars/1', $fileContents);

Rackspace

Storage::disk('rackspace')->put('avatars/1', $fileContents);

Thao tác với các file

Để lấy nội dung file:

$contents = Storage::get('file.jpg');

Để kiểm tra file có tồn tại không

Storage::exists('file.jpg');

Để lấy URL của file

$url = Storage::url('file1.jpg');

Lưu tạm file (chỉ hỗ trợ s3 và rackspace)

$url = Storage::temporaryUrl(
    'file1.jpg', now()->addMinutes(5)
);

File Metadata

Bạn có thể lấy thông tin của 1 file bằng cách sử dụng:

Storage::getMetaData('file.txt');

Lấy size:

$size = Storage::size('file1.jpg');

Lấy thời gian thao tác cuối

$time = Storage::lastModified('file1.jpg');

Copy và moving file

Storage::copy('old/file1.jpg', 'new/file1.jpg');
Storage::move('old/file1.jpg', 'new/file1.jpg');

Upload file

Chắc hẳn bạn đã từng làm qua tính năng upload file, hay ít nhất là upload avatar cho user hoặc thumbnail cho sản phẩm chẳng hạn. Laravel hỗ trợ bạn làm điều này một cách dễ dàng thông qua Request:

$path = $request->file('avatar')->store('public/avatars');

Hoặc thông qua Storage:

$path = Storage::putFile('avatars', $request->file('avatar'));

Lưu ý: mặc định với cách này Laravel sẽ lưu file dưới 1 unique name. Bạn có thể lấy filename bằng cách sử dụng:

$request->file('avatar')->hashName();

Upload dưới tên khác

Như cách ở trên thì Laravel sẽ tự động thêm tên cho file mà không trùng tên với các file có sẵn. Nhưng bạn cũng có thể lưu file với một tên tùy ý bằng cách sử dụng:

$path = $request->file('avatar')->storeAs(
    'avatars', $request->user()->id
);

Hoặc

$path = Storage::putFileAs(
    'avatars', $request->file('avatar'), $request->user()->id
);

Upload vào ổ đĩa khác

Ví dụ bạn muốn upload lên Amazon S3:

$path = $request->file('avatar')->store(
    'avatars/'.$request->user()->id, 's3'
);

Xóa file

Bạn có thể xóa file bằng cách sử dụng:

Storage::delete('file.jpg'); // Xóa 1 file
Storage::delete(['file1.jpg', 'file2.jpg']); // Xóa nhiều file

Hoặc xóa file trên Amazone S3:

Storage::disk('s3')->delete('folder_path/file_name.jpg');

Thao tác với thư mục

Lấy các file trong thư mục

$files = Storage::files('path');

Lấy tất cả các file con trong thư mục cùng với tất cả các file trong các thư mục con

$files = Storage::allFiles('path');

Tạo thư mục

Storage::makeDirectory('ten-thu-muc');

Xóa thư mục

Storage::deleteDirectory($directory);

Nguồn: https://laravel.com/docs/5.5/filesystem

Last updated