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|IlluminateHttpJsonResponse
*/
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 existnLINE 1: select count(*) as aggregate from "users" where "email" = $1n ^ (SQL: select count(*) as aggregate from "users" where "email" = [email protected])"
}
please help me
3
Answers
Instead of:❌
Use this:✅
Note the table name defined in your
User
Model isuser
.Hence, that has to be reflected in your validation rules as well.
You forget to check you table in in validation
'email'=>'required|email|unique:users,email',
replace users to user
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’