i'm new in laravel php and i try to create a new user with api post request and when i send this request i have a porblem when i do it I use psgql and laravel 9. i use that link to do this and custom somthing
This is my code: i has User model like
class User extends Authenticatable
{
use HasApiTokens,HasFactory, Notifiable;
public $timestamps = false;
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
and here is my AuthController to create new user
class AuthController extends Controller
{
/**
* Create User
* @param Request $request
* @return User|\Illuminate\Http\JsonResponse
*/
public function createUser(Request $request){
try{
$validateUser = Validator::make($request->all(),[
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email|unique:users,email',
'password'=>'required'
]);
if($validateUser->fails()){
return response()->json([
'status'=>false,
'message'=>'validation error',
'errors'=>$validateUser->errors()
],401);
}
$user = User::create([
'first_name'=>$request->first_name,
'last_name'=>$request->last_name,
'email'=>$request->email,
'password'=> Hash::make($request->password)
]);
return response()->json([
'status'=>true,
'message'=>'User created successfully',
'token'=>$user->createToken("API TOKEN")->plainTextToken
],200);
}
catch (\Throwable $th){
return response()->json([
'status'=>false,
'message'=>$th->getMessage()
],500);
}
}
}
and i got problem when i send post request json like
{
"status": false,
"message": "SQLSTATE[42P01]: Undefined table: 7 ERROR: relation \"users\" does not exist\nLINE 1: select count(*) as aggregate from \"users\" where \"email\" = $1\n ^ (SQL: select count(*) as aggregate from \"users\" where \"email\" = [email protected])"
}
please help me
CodePudding user response:
Instead of:❌
'email'=>'required|email|unique:users,email',
Use this:✅
'email'=>'required|email|unique:user,email',
Note the table name defined in your User
Model is user
.
Hence, that has to be reflected in your validation rules as well.
CodePudding user response:
You forget to check you table in in validation
'email'=>'required|email|unique:users,email',
replace users to user
CodePudding user response:
You are using the wrong table name in the validation, you need to replace 'users' by 'user' :
'email'=>'required|email|unique:users,email' to be 'email'=>'required|email|unique:user,email'