LaravelLaravl 5.7

Easy Four Steps To Upload Image in Laravel for Beginners

Easy Four Steps To Upload Image in Laravel for Beginners

Laravel
193Views

Hello to all, welcome to therichpost.com. In this post, I will share, Easy Four Steps To Upload Image in Laravel for Beginners.

I am feeling happy to share this code for laravel Beginners and this will definitely help. When I came new in Laravel, I hardly managed Image upload because I was beginners and not easily get simple tutorial for image upload in laravel.

But now I am doing for laravel beginners.

Here is the Easy Four Steps To Upload Image in Laravel and you can write this

code into your laravel project controller file:

 

1. You may determine if a file is present on the request using the hasFile method:

This will check file is present after form post and you need right all code inside this code:

if ($request->hasFile('photo')) {
    //your code
    }
2. Validate File:

Just validate the file with image extensions:

$image = $request->file('photo');
$valid_extensions = ['jpg','jpeg','png'];

if ( ! in_array($image->getClientOriginalExtension(), $valid_extensions) ){
    //you code for not success
}
3. Image Set Name:

I set name with date time because of uniqueness:

$imagename   = date('His').'-'.$image->getClientOriginalName();
4. Upload image into folder:

In public from, I have made gallery-images folder inside img folder:

$file->move(public_path('img/gallery-images'), $imagename);
5. Final Code:
use File;
public function addgallery(Request $request){
if ($request->hasFile('photo')) {
      $image = $request->file('photo');
      $valid_extensions = ['jpg','jpeg','png'];

      if ( ! in_array($image->getClientOriginalExtension(), $valid_extensions) ){
         dd('you code for not success');
      }
      else
      {
        $imagename   = date('His').'-'.$image->getClientOriginalName();
        $file->move(public_path('img/gallery-images'), $imagename);
      }
    }
}

 

This is it. If you have any query related to this post, then please comment below or ask questions.

Thank you,

jatt,

theRichPost

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

Leave a Reply

Positive SSL