Image Upload in Laravel 5

This article will show how to easily upload any kinds of files in Laravel. Here is a small web app where trying to upload images and perform some obligatory actions.

Step 1: Create Model, Migration and Controller

php artisan make:model Image

app/Image.php

First we have to make our model, that how our controller and route file will relate to database.

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model {
    protected $table = 'images';
    protected $fillable = [
        'title',
        'description',
        'image'
    ];
}

 

php artisan make:migration create_images_table --create --table=images

database/migration/xxxx_create_images_table.php

It’s time to make our table through database migration.

<?php

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

class CreateImagesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->string('filePath');
            $table->timestamps();
        });
    }

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

}

 

php artisan make:controller ImageController

app/Http/Controllers/ImageController.php

Creating ImageContoller where we have 3 methods like: 

  • Upload which redirecting our request to actual form structure or form view page. 
  • Store for validation, storing records into database and moving file into the specific path.
  • Show method for show all images to individual view page.
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use Guzzle\Tests\Plugin\Redirect;
use App\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

class ImageController extends Controller {

	/**
	 * Show the form for uploading a new resource.
	 *
	 * @return Response
	 */
	public function upload(){
		// Redirect to image upload form
   	}

	/**
	 * Store a newly uploaded resource in storage.
	 *
	 * @return Response
	 */
	public function store(){
		// Store records process
   	}

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function show(){
		// Show lists of the images
    }
}

 

Step 2: Image upload form with title, description and image name.

app/Http/routes.php

Url http://localhost:8000/imageUploadForm redirecting to image upload view page.

Route::get('imageUploadForm', 'ImageController@upload' );

ImageController upload method 

<?php

	/**
	 * Show the form for uploading a new resource.
	 *
	 * @return Response
	 */
	public function upload()
	{
      		 return view('imageupload');
	}

resources/views/imageuload.blade.php

Ok, Take a look of image upload form -
There are success message will show after upload a image successfully. Form open has action attribute which sends our form values to ImageController store method and finally we have errors variable, Will appear when error exist.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

</head>
<body>
    <h1 class="well well-lg">Upload Image</h1>
    <div class="container">
    @if(isset($success))
        <div class="alert alert-success"> {{$success}} </div>
    @endif
        {!! Form::open(['action'=>'ImageController@store', 'files'=>true]) !!}

        <div class="form-group">
            {!! Form::label('title', 'Title:') !!}
            {!! Form::text('title', null, ['class'=>'form-control']) !!}
        </div>

        <div class="form-group">
            {!! Form::label('description', 'Description:') !!}
            {!! Form::textarea('description', null, ['class'=>'form-control', 'rows'=>5] ) !!}
        </div>

        <div class="form-group">
            {!! Form::label('image', 'Choose an image') !!}
            {!! Form::file('image') !!}
        </div>

        <div class="form-group">
            {!! Form::submit('Save', array( 'class'=>'btn btn-danger form-control' )) !!}
        </div>

        {!! Form::close() !!}
        <div class="alert-warning">
            @foreach( $errors->all() as $error )
               <br> {{ $error }}
            @endforeach
        </div>
    </div>
</body>
</html>

 

Step 3: form validation, Image values storing to the database and moving original image to the specific path. 

app/Http/routes.php

Route::post('imageUploadForm', 'ImageController@store' );

ImageController store method

<?php
/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store(Request $request)
	{
        $image = new Image();
        $this->validate($request, [
            'title' => 'required',
            'image' => 'required'
        ]);
        $image->title = $request->title;
        $image->description = $request->description;
		if($request->hasFile('image')) {
            $file = Input::file('image');
            //getting timestamp
            $timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
            
            $name = $timestamp. '-' .$file->getClientOriginalName();
            
            $image->filePath = $name;

            $file->move(public_path().'/images/', $name);
        }
        $image->save();
        return $this->create()->with('success', 'Image Uploaded Successfully');
	}

 

Step 4: Show all images links, Images can be downloaded after clicking on those links.

app/Http/routes.php

Route::get('showLists', 'ImageController@show' );

ImageController show method

<?php
/**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function show(Request $request)
    {
        $images = Image::all();
        return view('image.showLists', compact('images'));

    }

resources/views/showLists.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

</head>
<body>

<h1 class="well well-lg">All Image List</h1>
@foreach( $images as $image )
    <div class="table table-bordered bg-success"><a href="{!! '/images/'.$image->filePath !!}">{{$image->filePath}}</a></div>
@endforeach

</body>
</html>

 

Something to say? Tell us in comment section.