Image not uploading in laravel 8 didn't take hasFile

1k views Asked by At

I am trying to upload an image and save it into a folder and database. But when I submit the form get all the data including the image file name but the image is not saved. In the database save as a null it did;t get the image as a file when I echo inside the image if the condition returns false why?? Here is the code

Blade

<form class="pt-3" action="{{url('registration_form')}}" method="post">
@csrf
    <div class="form-group">
        <input type="file" id="img" name="image" accept="image/*">
    </div>
    <div class="form-group">
        <input type="text" name="name" class="form-control form-control-lg" placeholder="Enter your name" required>
    </div>
    <div class="form-group">
        <input type="email" name="email" class="form-control form-control-lg" placeholder="Email" required>
    </div>
    <div class="mt-3">
        <input class="btn btn-block btn-primary btn-lg font-weight-medium auth-form-btn" type="submit" value="SIGN UP">
    </div>
    <div class="text-center mt-4 font-weight-light">
        Already have an account? <a href="{{url('login')}}" class="text-primary">Login</a>
    </div>
</form>

Controller

public function registration_form(Request $request)
{
    $user = new User;
        
    if ($request->hasFile('image')) {
        $image_tmp = $request->file('image');
        
        if ($image_tmp->isValid()) {
          
            $image_name = $image_tmp->getClientOriginalName(); //get the image name
            $extension = $image_tmp->getClientOriginalExtension(); //get extention of the image
            $imageName = $image_name . '-' . rand(111, 99999) . '.' . $extension;
            $large_image_path = 'assets/images/profile' . $imageName;
                
            Image::make($image_tmp)->save($large_image_path);
            $user->image = $imageName; 
         }
     }

     $user->save();
}

When echo the $request data

Array
(
    [_token] => 6xqdpIfqWBNMu0nifm91wM1lXpul0BRqoCTtEPmx
    [image] => ERD.png
    [name] => Amelia Alvarado
    [email] => [email protected]
)
1

There are 1 answers

0
Bhargav Chudasama On BEST ANSWER

You have missed enctype="multipart/form-data"

The enctype attribute specifies how the form-data should be encoded when submitting it to the server.

<form class="pt-3" action="{{url('registration_form')}}" method="post" enctype="multipart/form-data">
</form>