I use a trait to upload files. This trait has two public functions: upload(), store();
use Upload;
public function uploadAvatar(UploadRequest $request)
{
$this->upload($request->file('file'), 'useravatars');
$this->store();
return response()->json('');
}
There are two cases when the first method fails and the second. How to collect the typical result as an error or success and return it?
Exactly I can use try/catch.
CodePudding user response:
Like what's been said before, use a try/catch block.
use Upload;
public function uploadAvatar(UploadRequest $request)
{
$success = true;
$errorMessage = '';
try {
$this->upload($request->file('file'), 'useravatars');
$this->store();
} catch (\Exception $e) {
$success = false;
$errorMessage = $e->getMessage();
}
return response()->json(['success' => $success, 'error' => $errorMessage]);
}