I have a "create" method
public function crear(Request $req) {
$rules = array(
'nombre' => 'required',
);
$validator = Validator::make ( Input::all (), $rules );
if ($validator->fails()){
return Response::json(array('errors' => $validator->getMessageBag()->toArray()));
}else{
try{
$cargos = new Cargos();
$cargos->nombre = $req->nombre;
$cargos->save();
return response()->json($cargos);
}catch(\Illuminate\Database\QueryException $e){
return $e->getBindings();
}
}
}
I get the value with jquery
success: function(data) {
if((data.errors)){
alert(data.errors.nombre);
}else{
if(data){
alert("Error: "+data);
}else{
VolverANumerar();
}
}
},
but that code throws me this, when I try to register a value that is already registered in a table and the field has a unique type restriction:
Error: Operator,2016-11-01 14:55:51,2016-11-01 14:55:51
in the laravel api I got it to getBindings()
throw a code, it helped me with this:
try{
Cargos::find($req->id)->delete();
return response()->json();
}catch(\Illuminate\Database\QueryException $e){
return $e->getBindings();
}
but with the first no.
what I want is that in all the try/catch Exceptions I get a code thrown... it is not to show the user an sql error but something that he can understand. With the first code I try to register an item that is already registered and it returns the data that I tried to register, but it does not return a code as such for me to validate it. In the last code that I show, I delete an item that is being used in another table and the Exception throws me a 1. I validate it on the screen, if it is 1 then tell the user that he is trying to delete an item that is used.
I don't know if I haven't explained myself well yet. Excuse my clumsiness in not knowing how to explain myself well. First time I comment on a forum xD
In advance thanks for the help.
I don't exactly understand the problem, to know if it has been possible to save what you should check is the
save()
For example:
You also don't really need the
} else {
if the validator fails directly the is executedreturn
, so you can leave it like this:In either case, if you want to throw an exception when it doesn't save correctly, you modify the last
return
one with athrow
for the exception and you're good to go.Edit: Are you sure you are throwing the exception? Because from what you say, it doesn't seem that when you delete you are throwing an exception, it
1
's becausedelete
it went well.Do you have a screenshot of the Laravel error?
In any of the cases, the exception that you are trying to catch is
\Illuminate\Database\QueryException
so that if another one is thrown, you are not going to do itcatch
, or you add more or put a more generic one so that you can catch it for sure.