2
1

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 3 years have passed since last update.

Bytes to Humanreadable Laravel (File Upload Site #1)

Last updated at Posted at 2020-07-19

今回作ったファイルアプロードのサイトに関して記載して置こうと思います。
Laravelでファイルのサイズを
$file->getSize();で取るとByteで出てくるためそれをMb, Gb にする方法です。

1.App に Helpers フォルダーを作る。
Screen Shot 2020-07-19 at 12.59.29.png
2. そこにファイルを作る。名前は自由に。
Screen Shot 2020-07-19 at 13.00.34.png

3.そのファイルに下記を書きます。

SomeClass.php

<?php

namespace App\Helpers;

class SomeClass
{
    public static function bytesToHuman($bytes)
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];

        for ($i = 0; $bytes > 1024; $i++) {
            $bytes /= 1024;
        }

        return round($bytes, 2) . ' ' . $units[$i];
    }

4.SomeClass を app.php の aliases に入れます。
Screen Shot 2020-07-19 at 13.26.15.png
5.ターミナルで compose dump-autoload します. よってrequire()やinclude()を必要とせずにPHPクラスを使用できます。
Screen Shot 2020-07-19 at 13.28.42.png
6. 最後に view に使えます。
{{ \App\Helpers\SomeClass::bytesToHuman($file->size) }}
Screen Shot 2020-07-19 at 13.29.48.png

  • 結果
    Screen Shot 2020-07-19 at 13.32.53.png
    から
    Screen Shot 2020-07-19 at 13.33.10.png
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?