Site Admin
Site Admin Founder of MeaningArticles
2361 Views

Laravel 8 File Upload Tutorials

Hello Dev.

In this tutorial, I am going to learn you how to upload file in laravel 8. We will implement a file upload example for beginners in laravel 8 application. i will give you simple example of file upload in laravel 8. you will learn file upload in laravel 8.

Laravel 8 is just released at few days ago, Laravel 8 gives several new features and LTS support. So if you are new to laravel then this tutorial will help you create insert update delete application in laravel 8.

Here I will give you full example for how to upload file in laravel 8. So, let's follow few step to create example of laravel 8 file upload tutorial.


Step 1: Install Laravel 8

In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel blog


Step 2: Database Configuration

In second step, we will make database Configuration for example database name, username, password etc for file upload example of laravel 8 So lets open .env file and all deatils like as bellow

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)


Step 3: Create Migration

we are going to create file upload application for files. so we have to create migration for "files" table using Laravel 8 php artisan command, so first fire bellow command

php artisan make:migration create_files_table

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create files table

<?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');
    }
}

Now you have to run this migration by following command

php artisan migrate


Step 4: Add Route

Here, we need to add route for file upload. so open your "routes/web.php" file and add following route.

routes/web.php

use App\Http\Controllers\FileUploadController;

Route::get('file-upload', [ FileUploadController::class, 'fileUpload' ])->name('file.upload');
Route::post('file-upload', [ FileUploadController::class, 'fileUploadPost' ])->name('file.upload.post');


Step 5: Add Controller and Model

In this step, now we should create new controller as FileUploadController. So run bellow command and create new controller. bellow controller for create FileUploadController.

php artisan make:controller FileUploadController --model=File

After bellow command you will find new file in this path "app/Http/Controllers/FileUploadController.php".

In this controller will create two methods as bellow:

1.fileUpload()

2.fileUploadPost()

So, let's copy bellow code and put on FileUploadController.php file.

app/Http/Controllers/FileUploadController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class FileUploadController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function fileUpload()
    {
        return view('fileUpload');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function fileUploadPost(Request $request)
    {
        $request->validate([
            'file' => 'required|file|mimes:jpg,jpeg,bmp,png,doc,docx,csv,rtf,xlsx,xls,txt,pdf,zip',
        ]);
    
        $fileName = time().'.'.$request->file->extension();  
     
        $request->file->move(public_path('file'), $fileName);
  
        /* Store $fileName name in DATABASE from HERE */
        File::create(['name' => $fileName])
    
        return back()
            ->with('success','You have successfully file uplaod.')
            ->with('file',$fileName); 
    }
}

Ok, so after run bellow command you will find "app/Models/File.php" and put bellow content in File.php file

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;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
    ];
}


Step 6: Add Blade File

In last step. In this step we have to create just blade files. So mainly we have to create fileUpload file. So finally you have to create one following bellow blade file

fileUpload.blade.php

So let's just create following file and put bellow code.

resources/views/fileUpload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 File Upload example - meaningarticles.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<style type="text/css">
    h2{
        text-align: center;
        font-size:22px;
        margin-bottom:50px;
    }
    body{
        background:#f2f2f2;
    }
    .section{
        margin-top:150px;
        padding:50px;
        background:#fff;
    }
</style>    
<body>
    <div class="container">
        <div class="col-md-8 section offset-md-2">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h2>Laravel 8 file Upload example - meaningarticles.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>
                    @endif
                    @if (count($errors) > 0)
                        <div class="alert alert-danger">
                            <strong>Whoops!</strong> There were some problems with your input.
                            <ul>
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif
                    <form action="{{ route('file.upload.post') }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="row">
                            <div class="col-md-10">
                                <input type="file" name="file" class="form-control">
                            </div>
                 
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-success">Upload</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Now we are ready to run file upload example with laravel 8 so run bellow command for quick run

php artisan serve

Now you can open bellow URL on your browser

localhost:8000/file-upload

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.