skip to Main Content

I want to make a web service using PHP Laravel which can store images.
I have made a table testing containing a colum named Photo. Now I need to make a controller to save the photo file.

Testing Table:

Description (string) null
Photo (binary) null

In the controller:

public function store(Request $request)
{    
    $photo = $request->input('photo');

    $data = new Testing();
    $data->Photo = $photo;

    if ( $data->save() ) {
        $res['message'] = 'Success';
        $res['value'] = $data;

        return response ( $res );
    } else {
        $res['message'] = 'Failed';

        return response ( $res );
    }
}

But when I hit it using postman, I choose binary for the body and I choose a .jpg file, it throws me an error saying that my photo file is null.

Can you tell me how to get the photo path in the right way?

3

Answers


  1. You need to use this code to save photo

                if($request->hasFile('photo')){
                    $image = $request->file('photo');
                    $destination_path = public_path('/images/');
                    $source = "Image".time().'.'.$image->getClientOriginalExtension();
                    $image->move($destination_path, $source);
                }
                else{
                    $source = 'default.jpg';
                }
                $add_new_photo = new Photo();
                $add_new_photo->photo = $source;
                $add_new_video->created_by = Auth::user()->name;
                $add_new_video->save();
    

    This will save the photo in the images folder. Make sure you create the folder using 777 mode.

    Login or Signup to reply.
  2. You can do this :

    if($request->hasFile('photo')){
      $image = $request->photo->store('your_image_folder');
      $data->Photo = basename($image);
      ...
    }
    

    The store method will generate a unique ID to serve as the file name. If you want to name your file use

    $request->photo->storeAs('your_image_folder', 'your_filename')
    

    Then save $data

    Login or Signup to reply.
  3. try this instead of choosing binary in body.
    You need to choose form-data in body.
    and need to change the type of the field to form

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search