I was wondering on how to upload an image via API postman in Laravel and save to my database
which is phpMyAdmin. When I try to run my code in postman, this is what is showing:
"image null"
This is currently my code:
Banner CRUD Controller:
<?php
namespace AppHttpControllersApi;
use AppHttpControllersController;
use AppModelsBanner;
use IlluminateHttpRequest;
class BannerCRUDController extends Controller
{
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function index()
{
$banners = Banner::all();
return response($banners,200);
}
/**
* Show the form for creating a new resource.
*
* @return IlluminateHttpResponse
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function store(Request $request)
{
$data = $request->validate([
'id'=>'required',
'web_banner_profile'=>'required',
]);
$image = $request->file('image');
if($request->hasFile('image')) {
$new_name = rand() . '.' . $image->getClientOriginalExtension();
return response()->json($new_name);
}else{
return response()->json('image null');
}
$banners = Banner::create($data);
return response ($banners, 200);
}
/**
* Display the specified resource.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param IlluminateHttpRequest $request
* @param int $id
* @return IlluminateHttpResponse
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function destroy($id)
{
//
}
}
Banner Model:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Banner extends Model
{
public $table = "webinar";
use HasFactory;
protected $fillable = [
'id',
'web_banner_profile',
];
}
Any ideas as to what I’ve done wrong, I want to get this right now, as I’ve got a lot of tables I need to create.
Hope someone can help me to get started. Thanks a lot.
3
Answers
You just use this code to upload an image and in postman select type file
The error is clear request has empty image. So You should select key type file in postman
Replace store function with below in your BannerCRUDController.php.
Create
images
directory in storage.Image will be uploaded in
storage/images
.