1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ログイン必須なLaravelシステムでファイルの保存と取得を行う

1
Posted at

ログイン必須なLaravelシステムでファイルの保存と取得を行う

ログイン必須なLaravelシステムでファイルの保存と取得の方法を軽く調べてみました。

要約

だいたいドキュメントに書いてある。。。

  • Storageを使う
  • ファイルの操作はLaravelのドキュメントの通り。
  • ファイルの保存場所のシンボリックリンクをpublicに作らない
  • コントローラでファイルを取得して返す

やりたいこと

  • Laravelでファイルの保存と取得
  • ファイルはログイン済みのユーザのみが見れる
    • 非ログインユーザは見れない

方法

authのミドルウェアを指定したコントローラを経由してファイルを返すようにする。

ファイルの保存

use Illuminate\Support\Facades\Storage;
Route::group(['middleware' => 'auth'], function() {
  Route::get('/', function() {
    $content = "hello world\n";
    Storage::put('test.txt', $content);
    return "saved!";
  });
});

これで$contentの内容がstorage/app/text.txtに保存される。

ファイルの取得

use Illuminate\Support\Facades\Storage;
Route::group(['middleware' => 'auth'], function() {
  Route::get('/test.txt', function() {
    $content = Storage::get('test.txt');
    return $content;
  });
});

最後に

簡単にできた。あとは、コントローラでファイルに対しての認可を行ったりすれば、もっと複雑なことができそうです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?