How to upload image with validation in Laravel

Mahedi Hasan
Mar 27 · 3 min read

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 .

Upload imgage in Laravel

Step 1 : Install Laravel App

To do it run bellow command in your project directory.

After running this command create our migration

Step 2 : Create migration

For creating migration run bellow command

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

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

Now our database is ready . Now create route

Step 3 : Setup Route

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

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.

Step 5: Setup ImageController

Now go to your ImageController and paste those following code.

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.

That’s it. Hope you will enjoy this tutorial .

Mahedi Hasan

Written by

My name is Mahedi Hasan and I am a full-stack Web Developer and Software Developer. www.laramust.com is my official website.