I’m Submitting data through postman in Laravel. I need to show the null value if data do not insert during submitting(In JSON response). But It did not show the image in response I need to show an image response also Null
My Store Code is
public function store(Request $request) { $screenshots = new Screenshots ; $screenshots->user_id = $request->user_id; $screenshots->name = $request->name; $screenshots->size = $request->size; if($request->hasFile('image')){ $fileNameExt = $request->file('image')->getClientOriginalName(); $fileName = pathinfo($fileNameExt, PATHINFO_FILENAME); $fileExt = $request->file('image')->getClientOriginalExtension(); $fileNameToStore = $fileName.'.'.$fileExt; $pathToStore = $request->image->storeAs('public/uploads/screenshots', $request->image->getClientOriginalName()); $screenshots->image = $fileNameToStore; $screenshots->save(); }; $screenshots->save(); return $this->sendResponse($screenshots->toArray(), 'Command Send Successfully successfully.'); }
It is giving a null when any field is blank but if an image is blank I didn’t any response.
For more clear please see attached screenshot
Getting Response Be like
{"success":true,"data":{"user_id":"2","name":null,"size":"3.4kb","updated_at":"2020-02-12 07:26:49","created_at":"2020-02-12 07:26:49","id":32},"message":"Command Send Successfully successfully."}
The response I need if the image is also blank
{"success":true,"data":{"user_id":"2","name":null,"size":"3.4kb","image":"null","updated_at":"2020-02-12 07:26:49","created_at":"2020-02-12 07:26:49","id":32},"message":"Command Send Successfully successfully."}
Advertisement
Answer
please use below method to add default set null
// set in your model Screenshots
protected $attributes = array( 'image' => '', );
OR
if($request->hasFile('image')){ $fileNameExt = $request->file('image')->getClientOriginalName(); $fileName = pathinfo($fileNameExt, PATHINFO_FILENAME); $fileExt = $request->file('image')->getClientOriginalExtension(); $fileNameToStore = $fileName.'.'.$fileExt; $pathToStore = $request->image->storeAs('public/uploads/screenshots', $request->image->getClientOriginalName()); $screenshots->image = $fileNameToStore; $screenshots->save(); }else{ $screenshots->image = ''; }