Data File Folder Background

How to Make File Manager in Laravel?

File manager is a necessary component of every website these days. Laravel provides us out of the box file validation mechanism which is super easy to learn and implement. We can also save file names in database and retrieve them whenever we need to show them to the users. 

So let’s start,

1. Installing Laravel

First we need to install Laravel 8 by running this command.

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

2. Database Configuration

In order to configure the database we need to add these credentials in my .env file.

  • Database name
  • Database password
  • Database username
  • Database host

In order to do so, we will add the following lines in the .env file.

DB_HOST=localhost 
DB_DATABASE=file_manager_db 
DB_USERNAME=root 
DB_PASSWORD=secret

3. Creating model and migration

First we will create a model and migration by running this command.

php artisan make:model File -m

-m will create a migration file in your migration folder.

After running that command we will add this code in the migration file mentioned below. (Name of the file will be unique for everyone but location will be the same).

/database/migrations/2021_01_01_122345_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');
    }
}

Then we will run following command to run migration. It will create files table in the database.

php artisan migrate

Then we will have to add following code in our Image Model. app/File.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class File extends Model
{
	protected $fillable = [
		'name',
	];
}

4. Adding Routes

We will add 2 routes in our “routes/web.php” file. One to show uploaded images and other to upload multiple images. 

Route::get('file-manager', 'FilesController@fileManager')->name('file-manager');
Route::post('store-file', 'FilesController@storeFile')->name('file.store');

5. Creating Controller

Then we will create ImagesController by running following Laravel command in our terminal. 

php artisan make:controller FilesController

Then we will add following code to ImagesController.

app/Http/Controllers/FilesController.php 

<?php

namespace App\Http\Controllers;

use App\File;
use Illuminate\Http\Request;

class FilesController extends Controller {

	public function fileManager() {
		$files = File::all();

		return view( 'files.file_manager', [ 'files' => $files ] );
	}

	public function storeFile( 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( 'files' ), $fileName );
		File::create( [ 'name' => $fileName ] );

        return back()
	        ->with( 'success', 'You have successfully uploaded a file.' );
    }
}

6. Creating View 

Then we will add following code in our view file to show and upload images. 

resources/views/files/file_manager.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Laravel 8 File Manager - Laramatic.com</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script></head>
<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 Manager - Laramatic.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.store') }}" 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 class="row mt-3">
                    @foreach($files as $value)
                        <div class="col-md-2">
                            <img src="{{ asset('files/'.$value->name) }}" width="100%">
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Now run the following command to serve Laravel site. 

php artisan serve

Here is how it will appear in your browser.Â