I just ran into a problem where i can't seem to find a proper way of handling. I know this is a stupid example, but its the fastest i could think of.
UserController
trait SaveUser;
public function example(Request $request){
$user = $this->saveUser($request->name);
return $user;
}
Trait SaveUser;
public function saveUser($name){
$is_valid = $this->validateUser;
if(!is_valid) return response()->json(['data' => null,'message' => "please enter a name for the user",],500);
try{
$user = new User();
$user->name = $name;
$user->save()
return $user;
}catch(\Exception $e){
return response()->json(['data' => null,'message' => "error saving the user.",],500);
}
}
private function validateUser($name){
if($name == null)
return false;
return true;
}
Lets say i am saving a user, requesting the name from the api request. I send it to a trait because its going to be used in many places, if the user name is not valid, it returns a json response saying it needs to be set, else if an error occurs while saving the user, return a code 500
response. Now this is a simple example, on my case, i have the validate
method validate many other things and each have a unique message for a response, same for attributes of the user, etc..
So pretty much my problem is, that when the try catch
catches an execption or something is not valid, it returns return response()->json(['data' => null,'message' => "error saving the user.",],500);
to the $user
in the UserController variable. What i would like it to do is, end my code in the exception or in the return response()->
and return the response. Is there anyway i can just end the code anywhere that i have return response()->...
?
I am using this in an API, this is just a quick example. Any help would be appreciated. Thanks