Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views :
InvestmentNovel

Latest Programming Tutorial Blog

Laravel Image Upload With Validation Tutorial Example

/
/
/
79 Views

In this example, I will explain to you how to do Laravel Image Upload With Validation Tutorial Example.  Laravel 5.6 provides the very simple way to create file uploading with proper validation like max file size 2MB, valid file extension like jpeg, jpg, png, gif or svg, etc. We can also store the image in the database.

Laravel Image Upload With Validation Tutorial Example

We are going to Configure Laravel Project.

#1: Install Laravel Project

Establish Laravel 5.6 Project by the typing following command.

$ composer create-project --prefer-dist laravel/laravel laravelimageupload

#2: Configure SQL Database

Now we can setup database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=imageupload
DB_USERNAME=root
DB_PASSWORD=

#3: Build Model and Migration File

php artisan make:model Imageupload -m

It will create the Imageupload.php file and also create a create_imageuploads_table.php  migration file.

    public function up()
    {
        Schema::create('imageuploads', function (Blueprint $table) {
            $table->increments('id');
            $table->string('image');
            $table->timestamps();
        });
    }

#4: Create a View File

You can create a file in resources/views/imageupload.blade.php and put this following code in it.

<!-- imageupload.blade.php -->

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Laravel 5.6 Image Upload With Validation Tutorial Example</title> 
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
   <h2>Laravel 5.6 Image Upload With Validation Tutorial Example</h2>
   </br>
   @if (\Session::has('success'))
      <div class="alert alert-success">
        <p>{{ \Session::get('success') }}</p>
      </div><br />
      <img src="/images/{{Session::get('image') }}">
     @endif
    @if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
      @endif
     </br>
     <form action="{{ url('imageupload') }}" enctype="multipart/form-data" method="post">
       @csrf
		<div class="row">
		    <div class="col-md-12">
		      <input type="file" name="image" />
                      <button type="submit" class="btn btn-primary">Upload</button>
		    </div>
	        </div>
    </form>
  </div>
</body> 
</html>

#5: Create one controller

php artisan make:controller ImageUploadController

It will build the controller file called ImageUploadController.php.

//ImageUploadController.php

public function create()
    {
        return view('imageupload');
    }

#6: Define Route

We register all route in a web.php file.

Route::get('imageupload','ImageUploadController@image');
Route::post('imageupload','ImageUploadController@imagePost');

Laravel Image Upload With Validation Example

#7: Store data to the database

Next, we are set to fill in imagePost () method with the logic to store data to the database. Also, we can move the file to the images folder under a public directory. First, we define the validation for an image field. If the image field fails to validate then it through an error. If validation passes then data store to the database successfully. Put the following code in ImageuploadController under imagePost() method.

use App\Imageupload;


    public function imagePost(Request $request)
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);


        $imageName = time().'.'.$request->image->getClientOriginalExtension();
        $request->image->move(public_path('images'), $imageName);
        $imageupload = new Imageupload;
        $imageupload->image=$imageName;
        $imageupload->save();
        return back()
    		->with('success','Image has been Uploaded successfully.')
    		->with('image',$imageName);

    }

Laravel 5.6 Image Upload With Validation Example

Final Code of ImageuploadController looks like that.

//ImageUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Imageupload;

class ImageUploadController extends Controller
{
    public function image()
    {
        return view('imageupload');
    }

    public function imagePost(Request $request)
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);


        $imageName = time().'.'.$request->image->getClientOriginalExtension();
        $request->image->move(public_path('images'), $imageName);
        $imageupload = new Imageupload;
        $imageupload->image=$imageName;
        $imageupload->save();
        return back()
    		->with('success','Image has been Uploaded successfully.')
    		->with('image',$imageName);

    }
}

You can see the database in below screenshot.

Laravel 5.6 Image Upload With Validation Tutorial

At last, our Laravel Image UploadWith Validation Tutorial Example is over.

  • Facebook
  • Twitter
  • Google+
  • Linkedin
  • Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This div height required for enabling the sticky sidebar