I want to insert a new record in a table of my database and I want to validate each of the fields in the request but it doesn't work for me.
This is my UserController.php
<?php
namespace App\Http\Controllers;
use App\User;
use App\Persona;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class UserController extends Controller
{
public function registro(Request $request){
$request->validate([
'nombre'=> 'required',
'apellidos'=> 'required',
'email'=> 'required|email',
'edad'=> 'required',
'genero'=> 'required',
'password'=> 'required',
]);
$persona = new Persona;
$persona->nombre = $request->input('nombre');
$persona->apellidos = $request->input('apellidos');
$persona->email = $request->input('email');
$persona->edad = $request->input('edad');
$persona->genero = $request->input('genero');
if($persona->save()){
$user = new User;
$user->persona_id = $persona->id;
$user->name = $persona->nombre;
$user->email = $persona->email;
$user->password = Hash::make($request->input('password'));
if($user->save()){
return response()->json(["User"=>$user],201);
}
}
return abort(400, "Error al registrar");
}
}
and to be use of this, I use my route:
Route::post('/registro', 'UserController@registro');
I use insomnia to do the test, where in the request that I send it is empty and it gives me answers like this:
And it should show me an error because the fields are required but not.
For Laravel to detect that what you are doing is an api request, it asks you to add as header
Accept: application/json
, by adding this, Laravel will know whether to throw a 200, or a 422 error.I would recommend you to create a middleware, in which you force the header to be sent, maybe.
php artisan make:middleware forceJsonHeader
We would edit it like this:
We add it to
app/Http/Kernel.php
:You would only have to use it on your routes.