Search code examples
phplaravellaravel-passport

Laravel: Passport API with accept image


So I have already a working api using laravel passport

in my controller named as AuthController.php

I have this working code of saving data

    public function activity_log(Request $request){

    $validatedData = $request->validate([
        'projCode'=>'required',
        'activity_desc'=>'required',
        'type'=>'required'
    ]);

    $tbl_projectlist = DB::connection('mysql')->select("SELECT * from tbl_projectlist WHERE proj_code = '".$request->projCode."'");

    if(empty($tbl_projectlist))
    {
        return response([
            "status"=>"bad",
            "message"=>"Invalid projCode doesn't exists."
        ]);
    }
    else if($request->type == "REPORT" || $request->type == "ISSUE")
    {
        $ActivityLog = new ActivityLog;
        $ActivityLog->projCode = $request->projCode;
        $ActivityLog->activity_desc = $request->activity_desc;
        $ActivityLog->type = $request->type;
        $ActivityLog->attachment = "/img/default-image.jpg";
        $ActivityLog->created_by_id = Auth::user()->company_id;
        $ActivityLog->created_by_name = Auth::user()->name;
        $ActivityLog->created_at = now();
        $ActivityLog->updated_at = now();
        $ActivityLog->save();

        return response([
            "status"=>"ok",
            "message"=>"Activity successfully submitted!"
        ]);
    }
    else
    {
        return response([
            "status"=>"bad",
            "message"=>"Invalid choose REPORT or ISSUE"
        ]);
    }

}

and in my api.php

Route::post('/login','Auth\Api\AuthController@login');

Route::middleware('auth:api')->group(function () {

     Some routes...

     Route::post('/activity_log','Auth\Api\AuthController@activity_log');
});

As of now i'm just storing the file path of the image hard coded which the img is located.

What I'm trying to do is to accept img file and save to my folder and store the file path in my database

I'm using postman to test my api with this

enter image description here


enter image description here


Solution

  • From postman: use POST method, select body and form-data, select file and use image as key after that select file from value which you need to upload.

    public function uploadTest(Request $request) {
    
        if(!$request->hasFile('image')) {
            return response()->json(['upload_file_not_found'], 400);
        }
        $file = $request->file('image');
        if(!$file->isValid()) {
            return response()->json(['invalid_file_upload'], 400);
        }
        $path = public_path() . '/uploads/images/store/';
        $file->move($path, $file->getClientOriginalName());
        return response()->json(compact('path'));
     }