I have a problem when adding a record to the database. When I receive a 200 response code with redirected: true, the record is not added to my users table. However, if I receive a 204 response with redirected: false, the record is added successfully.
I also noticed in Postman that if I log out and then register again, I receive a 204 response code.
//Register.jsx
async function handleRegister(e) {
e.preventDefault();
await fetch('http://localhost:8000/sanctum/csrf-cookie', {
method: "GET",
credentials: "include"
});
// Extract CSRF token
const csrfToken = decodeURIComponent(
document.cookie.split('; ').find(row => row.startsWith('XSRF-TOKEN='))?.split('XSRF-TOKEN=')[1] || ''
);
console.log(csrfToken);
const res = await fetch('http://localhost:8000/register', {
method: "POST",
headers: {
"X-XSRF-TOKEN": csrfToken
},
credentials: "include",
body: JSON.stringify(formData),
});
if (!res.ok) {
console.error("Registration failed:", res);
if (res.errors) {
setErrors(res.errors);
console.error("Errors:", res.errors);
}
} else {
navigate("/login");
console.log(res);
}
}
//RegisteredUserController.php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
class RegisteredUserController extends Controller
{
/**
* Handle an incoming registration request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): Response
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->string('password')),
]);
event(new Registered($user));
Auth::login($user);
return response()->noContent();
}
}
//auth.php
Route::post('/register', [RegisteredUserController::class, 'store'])
->middleware('guest')
->name('register');
I have a problem when adding a record to the database. When I receive a 200 response code with redirected: true, the record is not added to my users table. However, if I receive a 204 response with redirected: false, the record is added successfully.
I also noticed in Postman that if I log out and then register again, I receive a 204 response code.
//Register.jsx
async function handleRegister(e) {
e.preventDefault();
await fetch('http://localhost:8000/sanctum/csrf-cookie', {
method: "GET",
credentials: "include"
});
// Extract CSRF token
const csrfToken = decodeURIComponent(
document.cookie.split('; ').find(row => row.startsWith('XSRF-TOKEN='))?.split('XSRF-TOKEN=')[1] || ''
);
console.log(csrfToken);
const res = await fetch('http://localhost:8000/register', {
method: "POST",
headers: {
"X-XSRF-TOKEN": csrfToken
},
credentials: "include",
body: JSON.stringify(formData),
});
if (!res.ok) {
console.error("Registration failed:", res);
if (res.errors) {
setErrors(res.errors);
console.error("Errors:", res.errors);
}
} else {
navigate("/login");
console.log(res);
}
}
//RegisteredUserController.php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
class RegisteredUserController extends Controller
{
/**
* Handle an incoming registration request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): Response
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->string('password')),
]);
event(new Registered($user));
Auth::login($user);
return response()->noContent();
}
}
//auth.php
Route::post('/register', [RegisteredUserController::class, 'store'])
->middleware('guest')
->name('register');
Share
Improve this question
asked Mar 13 at 13:05
AngelicaAngelica
371 silver badge9 bronze badges
1
|
1 Answer
Reset to default 2it doesn't matter if you register again even if never logged in. registering the same user results in a failure in the body payload validation:
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
as you can see the email must be unique. In addition i would recomend to return a 201 status code for successfully created resources in the database. Try with a response like this, to handle request meant for json responses and for webapp navigation:
return $request->wantsJson()
? new JsonResponse([], 201)
: redirect($this->redirectPath());
migrate:fresh
and register, I receive a 204 response code. However, when I try to register again, I get a 200 response, even though I haven't logged in yet. – Angelica Commented Mar 13 at 13:17