I'm trying to make a custom Auth controller with this code:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function register(Request $request)
{
//validate the request
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8|confirmed',
]);
$data = $request->all();
//create new user
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
//return response
return response()->json(['message' => 'Successfully created user!'], 201);
}
}
the controller should create a new User entry inside the database, the User Model is Laravel's default one, no change has been made.
In my api.php routes file I have this simple routes setup:
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/register', [AuthController::class, 'register']);
the problem is that when I try to send a POST request to /api/register Laravel responds with the default html page:
what am I doing wrong here? Consider that this should be only the back-end of my app so I don't need to setup any view
CodePudding user response:
In your register method you have validation. If validation fails, it returns you back with validation errors. So you have an error in your $request fields somewhere.
Name should be string, email must be a valid email and should be unique, meaning that none of the existing users should have it. For password you must have confirmation, and that's where i think the problem is.
You should pass to this GET API route not only 'name', 'email' and 'password', but also 'password_confirmation' field which contains same password as 'password' field. I suggest for you to remove this rule to simplify the request, like this :
//validate the request
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
]);