Surfe.be - passive income

How to upload image with validation in Laravel

How to upload image

Today, i will show you how to create simple image upload in laravel. I write article step by step about image upload in laravel. I also added validation with image upload in laravel. Here i will follow object oriented php structure to upload imgae. It is very easy and preety awesome . Here i also validate image where user can only upload jpeg,png,jpg,gif type image. So doing it you can download a fresh laravel file or you can do it in your current running project. So just follow few steps. Here i will use a fresh laravel app .

laravel-image-upload

Step 1 : Install Laravel  App

To do it run bellow command in your project directory.

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

After running this command create our migration

Step 2 : Create migration

For creating migration run bellow command

php  artisan make:model Image -m -r

Then go to migration table database/migrations/images.php and paste the following code.

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

class CreateImageTable extends Migration
{
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('image');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Then connect your database and migrate your database using below command.

php artisan migrate

Now our database is ready . Now create route

Step 3 : Setup Route

go to your routes/web.php and paste the following code

 Route::resource('image','ImageController');

Now we have to create a trait. If you don’t know what is trait in php then please read this article before.

What is Traits in PHP ?

Here we want to create a trait because , if you upload a image using trait then you can use this trait method any where to upload file. Just you have to use this trait in your controller . That’s it. It’s awesome i think.

Step 4: Create a Trait

Go to your app folder and create a folder name Traits and whose namespace will be App/Traits/ImageUpload.php . Create it manually , not using command line .Now paste this following code to your traits file.

namespace App\Traits;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

trait ImgaeUpload
{
    public function UserImageUpload($query) // Taking input image as parameter 
    {
        $image_name = str_random(20);
        $ext = strtolower($query->getClientOriginalExtension()); // You can use also getClientOriginalName()
        $image_full_name = $image_name.'.'.$ext;
        $upload_path = 'image/';    //Creating Sub directory in Public folder to put image
        $image_url = $upload_path.$image_full_name;
        $success = $query->move($upload_path,$image_full_name);

        return $image_url; // Just return image
    }
}

Step 5: Setup ImageController

Now go to your ImageController and paste those following code.

namespace App\Http\Controllers\ImageController

use App\Http\Controllers\Controller;
use App\Image;
use App\Traits\ImageUpload; 
use Illuminate\Http\Request;

class ImageControllerextends Controller{   

    use ImageUpload; //Using our created Trait to access inside trait method

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

        $data = new Image;

        $data->image = $request->image;
        if($data->image){
           try {       
            $filePath = $this->UserImageUpload($data->image); //Passing $data->image as parameter to our created method 
            $data->image = $filePath;
            $data->save();
            return redirect()->back();  
           
       } catch (Exception $e) {
           //Write your error message here
       }
     }      
 }
}

Hope you will understand all the procedures.

Step 6 : Retrive Image from database

Now we our ready to show our image in blade file. Just follow like below. Now just print all the image from database in your controller and print like that in blade file.

<img src="/{{ $YourVariableName->image }}" style="height: 70px; width: 70px; border-radius: 50%;">

That’s it. Hope you will enjoy this tutorial . If you like this tutorial , please share and don’t forget to share your experience. If you wanna learn more about file upload then you can visit here and read thid documentation.

Leave a comments

LET'S SOCIALITE

Recent Tweets