Returning a file (image or pdf) in restful api

It is achieved in two simple steps like below after running artisan command for making new controller named FileController.php ( php artisan make:controller FileController )

Step 01: Setting up route for file downloading

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

Route::get( '/files/get', [FileController::class, 'show'] );

Step 02: Creating show() method in FileController

public function show() {
   return response()->download( public_path( 'img' ).'/wallpapers-01.jpg', 'Nice island' );
}


Above, when user browses url http://localhost:8000/file/get in their browser an image file named Nice island.jpg will be downloaded. Before that you need to create a folder named img inside public folder and keep an image named "wallpapers-01.jpg" there.

Related Posts


Building RESTful APIs in Laravel

Seeding Poll data

Seeding Question data for a poll

Pagination for poll in restful api

Uploading image in restful api