Uploading image in restful api

It is achieved in two simple steps like below in FileController.php

Step 01: Setting up route for file uploading

//at the top 
use App\Http\Controllers\FileController;

Route::post( '/files/create', [FileController::class, 'create'] );

Step 02: Creating create() method in FileController

// image uploads in public img folder
public function create( Request $request ) {

	if ($file = $request->file('photo')) {
		$postImage = date('ymdihs') . '.' . $file->extension();
		$file->move(public_path( 'img' ),$postImage);
		
		return response()->json([
			"success" => true,
			"message" => "File successfully uploaded",
			"file" => asset( "img/{$postImage}" )
		]);

	}        
} 


Now in postman application under "Body" tab selecting "form-data" putting key value pair as "photo" and "image filename" ( changing input type from text to file  ) and setting HTTP verb as POST if url is browsed like below this in local server the given image file will be updated to img folder which is located inside public folder.

EndPoint URL: http://localhost:8000/api/files/create
HTTP verb: POST
Input:
key: photo
file: imageName

Another way file upload can also be implemented that is storing file in storage/app folder. However, using symlink we need to link that to our  
public/storage folder by running this artisan command - php artisan storage:link

After that we need to modify our create() method above like below.

public function create( Request $request ) {

	if ( $file = $request->file('photo') ) {
		$fileName = date('ymdihs') . '.' . $file->extension();
		request()->file( 'photo' )->storeAs( 'public/img/' . $fileName, '' );

		return response()->json([
			"success" => true,
			"message" => "File successfully uploaded",
			"file" => asset( "img/{$fileName}" )
		]);            
	}               
}


This method although uploads the image in storage/app/img folder however, because of symlink the images will also be linked under public/storage/img folder which will be then publicly accessible.

Later this uploaded image can be accessed in blade template using following snippet

<img src="{{ asset('/storage/img/filename.jpg') }}" />

Related Posts


Building RESTful APIs in Laravel

Seeding Poll data

Seeding Question data for a poll

Pagination for poll in restful api