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

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

**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](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

```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

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

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

```html
<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

```html
<!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ả:

![](https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FEhQn5jezFjvt4WVUeXeh%2FScreenshot_3.png?alt=media\&token=99511d49-1724-4c8a-a758-7ac618a74755)

### **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>
```

![
](https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FugpcjXQtj6UwZqUu0SUW%2FScreenshot_1.png?alt=media\&token=cb902a73-81a4-4a4b-9176-1a85c600bfe8)

### **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&#x20;

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

### Xem thêm tại: [Tìm hiểu về File Storage của Laravel](https://vantien.net/lap-trinh/php/laravel/tim-hieu-ve-file-storage-cua-laravel/) <a href="#xem-them-tai-tim-hieu-ve-file-storage-cua-laravel-0" id="xem-them-tai-tim-hieu-ve-file-storage-cua-laravel-0"></a>

## Giới thiệu <a href="#gioi-thieu-1" id="gioi-thieu-1"></a>

* 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](https://vantien.net/lap-trinh/php/laravel/tim-hieu-ve-file-storage-cua-laravel/). 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](https://github.com/thephpleague/flysystem).
* 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 <a href="#config-2" id="config-2"></a>

* Bạn có thể config File Storage tại file `config/filesystems.php`.
* Driver mà Laravel hỗ trợ: "local", "ftp", "sftp", "s3", "rackspace".

#### Local <a href="#local-3" id="local-3"></a>

* Để 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 <a href="#s3-driver-4" id="s3-driver-4"></a>

Để 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`:

```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 <a href="#ftp-driver-5" id="ftp-driver-5"></a>

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`:

```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 <a href="#thao-tac-voi-cac-disk-6" id="thao-tac-voi-cac-disk-6"></a>

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: <a href="#mac-dinh-7" id="mac-dinh-7"></a>

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

#### S3: <a href="#s3-8" id="s3-8"></a>

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

#### Rackspace <a href="#rackspace-9" id="rackspace-9"></a>

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

## Thao tác với các file <a href="#thao-tac-voi-cac-file-10" id="thao-tac-voi-cac-file-10"></a>

#### Để lấy nội dung file: <a href="#de-lay-noi-dung-file-11" id="de-lay-noi-dung-file-11"></a>

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

#### Để kiểm tra file có tồn tại không <a href="#de-kiem-tra-file-co-ton-tai-khong-12" id="de-kiem-tra-file-co-ton-tai-khong-12"></a>

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

#### Để lấy URL của file <a href="#de-lay-url-cua-file-13" id="de-lay-url-cua-file-13"></a>

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

#### Lưu tạm file (chỉ hỗ trợ s3 và rackspace) <a href="#luu-tam-file-chi-ho-tro-s3-va-rackspace-14" id="luu-tam-file-chi-ho-tro-s3-va-rackspace-14"></a>

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

#### File Metadata <a href="#file-metadata-15" id="file-metadata-15"></a>

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

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

Lấy size:

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

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

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

#### Copy và moving file <a href="#copy-va-moving-file-16" id="copy-va-moving-file-16"></a>

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

## Upload file <a href="#upload-file-17" id="upload-file-17"></a>

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:

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

Hoặc thông qua Storage:

```php
$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 <a href="#upload-duoi-ten-khac-18" id="upload-duoi-ten-khac-18"></a>

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:

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

Hoặc

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

#### Upload vào ổ đĩa khác <a href="#upload-vao-o-dia-khac-19" id="upload-vao-o-dia-khac-19"></a>

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

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

## Xóa file <a href="#xoa-file-20" id="xoa-file-20"></a>

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:

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

## Thao tác với thư mục <a href="#thao-tac-voi-thu-muc-21" id="thao-tac-voi-thu-muc-21"></a>

#### Lấy các file trong thư mục <a href="#lay-cac-file-trong-thu-muc-22" id="lay-cac-file-trong-thu-muc-22"></a>

```php
$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 <a href="#lay-tat-ca-cac-file-con-trong-thu-muc-cung-voi-tat-ca-cac-file-trong-cac-thu-muc-con-23" id="lay-tat-ca-cac-file-con-trong-thu-muc-cung-voi-tat-ca-cac-file-trong-cac-thu-muc-con-23"></a>

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

#### Tạo thư mục <a href="#tao-thu-muc-24" id="tao-thu-muc-24"></a>

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

#### Xóa thư mục <a href="#xoa-thu-muc-25" id="xoa-thu-muc-25"></a>

```php
Storage::deleteDirectory($directory);
```

> Nguồn: [https://laravel.com/docs/5.5/filesystem](https://laravel.com/docs/5.5/filesystem)
