Laravel 8 Upload Image To Storage Folder Example

Hello Artisan,

In this Laravel tutorial, I am going to show you how to upload images to storage and show them in the blade file in Laravel. You know that uploading files to storage rather than the public are more secure for your application. In this example, you will learn how to upload images in storage and after uploading how to laravel display image from storage in blade we will see.

Before uploading image, we will generate image type, image path, image size, and original image name. After getting all of that information we will save that image into the database and storage and finally, we will show that image in laravel blade file.

This Laravel 8 image upload tutorial will work for your Laravel 5, 6, 7, 8 applications. So if you don't know how to upload image to storage then this example is for your. Let's start:

 

Step 1: Create Model

In the first step, we will create a Model to save image into storage folder in Laravel. So create model by the following command:

php artisan make:model Gravatar -m

 

And update this Gravatar model like below:

app\Models\Gravatar.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Gravatar extends Model
{
    use HasFactory;

    protected $guarded = [];
}

 

And update the migrations file like below:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGravatarsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('gravatars', function (Blueprint $table) {
            $table->id();
            $table->string('media_name');
            $table->string('media_path');
            $table->string('media_size');
            $table->string('media_type');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('gravatars');
    }
}

 

Now run php artisan migrate command to create a table.

 

Step 2: Add Route

In this step, we have to add a route. So add it like below:

routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\MediaController;


Route::get('/',[MediaController::class,'index']);
Route::post('/',[MediaController::class,'store'])->name('store');

 

Step 3: Create Controller

Now in this step, we need to create media controller to save our image into database and storage folder before showing it in Laravel blade file. 

app\http\Controllers\MediaController.php

namespace App\Http\Controllers;

use App\Helper\Media;
use App\Models\Gravatar;
use Illuminate\Http\Request;

class MediaController extends Controller
{
    use Media;

    public function store(Request $request)
    {
        if($file = $request->file('media')) {
            $fileData = $this->uploads($file,'user/avatar/');
            $media = Gravatar::create([
                       'media_name' => $fileData['fileName'],
                       'media_type' => $fileData['fileType'],
                       'media_path' => $fileData['filePath'],
                       'media_size' => $fileData['fileSize']
                    ]);
        }
        return $media;
    }

    public function index(Gravatar $gravatar)
    {
        $data = $gravatar->first();
        return view('welcome',compact('data'));
    }

}

 

Step 4: Create Media Trait

Now in this step, we will create a media trait so that we can reuse our code. So create it like below:

app\Helper\Media.php

namespace App\Helper;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

trait Media {

    public function uploads($file, $path)
    {
        if($file) {

            $fileName   = time() . $file->getClientOriginalName();
            Storage::disk('public')->put($path . $fileName, File::get($file));
            $file_name  = $file->getClientOriginalName();
            $file_type  = $file->getClientOriginalExtension();
            $filePath   = 'storage/'.$path . $fileName;

            return $file = [
                'fileName' => $file_name,
                'fileType' => $file_type,
                'filePath' => $filePath,
                'fileSize' => $this->fileSize($file)
            ];
        }
    }

    public function fileSize($file, $precision = 2)
    {   
        $size = $file->getSize();

        if ( $size > 0 ) {
            $size = (int) $size;
            $base = log($size) / log(1024);
            $suffixes = array(' bytes', ' KB', ' MB', ' GB', ' TB');
            return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
        }

        return $size;
    }
}

 

Step 5: Create Blade

Now we are in the final step before ending this Laravel 8 image upload to storage folder tutorial. Now create a welcome file like below:

resources/views/welcome.blade.php

 

Recommended: Create Custom Trait to Resize and Upload Image in Laravel

 

Hope this laravel 8 upload image to storage folder and how to display image from subfolder in storage in laravel tutorial will help you.

 

#laravel #laravel-8x #image-upload