How to Make Media Manager in Laravel?

Laravel 8 provides us a very easy and reliable way to upload images to server. Here in this tutorial we will upload multiple images to the server. This can be used as media manager in your website.

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 mediaManager

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=media_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 Image -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 same). 

/database/migrations/2021_01_01_122345_create_images_table.php

<?php

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

class CreateImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
	        $table->string('name');
	        $table->timestamps();
        });
    }

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

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

php artisan migrate

Then we will have to add following code in our Image Model. 

app/Image.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image 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('media-manager', 'ImagesController@mediaManager')->name('media-manager');
Route::post('store-images', 'ImagesController@storeImages')->name('images.store');

5. Creating Controller

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

php artisan make:controller ImagesController

Then we will add following code to ImagesController.

app/Http/Controllers/ImagesController.php 

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use app\Image;

class ImagesController extends Controller {
	public function mediaManger() {
		$images = Image::all();

		return view( 'images.media_manager', [ 'images' => $images ] );
	}

	public function storeImages( Request $request ) {
		foreach ( $request->file( 'file' ) as $image ) {
			$imageName = $image->getClientOriginalName();
			$image->move( public_path() . '/images/', $imageName );
			$fileNames[] = $imageName;
			Image::create( [ 'name' => $imageName ] );
		}

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

}

6. Creating View 

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

resources/views/images/media_manager.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Laravel 8 Media 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 Media 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('images.store') }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    <div class="row">
                        <div class="col-md-10">
                            <input type="file" name="file[]" accept="image/*" multiple="multiple" 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($images as $value)
                                <div class="col-md-2">
                                    <img src="{{ asset('images/'.$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 are the final results. Â