Home Laravel Easy Four Steps To Upload Image in Laravel for Beginners

Easy Four Steps To Upload Image in Laravel for Beginners

by therichpost
0 comments
Laravel 7.2 routing with route group auth guard check with prefix

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

You may also like

Leave a Comment

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