I'm modifying the signup function that store user's data( email and password). I wish to include more data such as phone number, name and national ID. I tried but in mysql database it doesn't show anything. Here is what I have done :
public function signup(Request $request)
{
$credentials = $request->only([
'national_id' ,
'name' ,
'phone',
]);
$validator = Validator::make($credentials, [
'name' => 'required',
'email' => 'sometimes|email|unique:users',
'password' => 'sometimes|min:6|confirmed',
'password_confirmation' => 'sometimes|min:3',
'national_id' => 'required','unique:national_id',
]);
if ($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
try {
$user = $this->users->create($request->except('roles', 'permissions'));
if (!$user->id) {
return $this->response->error('could_not_create_user', 500);
}
$hasToReleaseToken = Config::get('boilerplate.signup_token_release');
if ($hasToReleaseToken) {
$user->national_id = $request->national_id;
return $this->login($request);
}
return $this->response->created();
} catch (\Exception $e) {
return $this->response->error($e->getMessage(), 500);
}
}
when I dd($request->national_id it shows me the national_id data in postman, but in my database it's NULL.
Related
i'm trying this updateorcreate method and for some reason id does not insert nothing into database, here is my code example, it enters into catch but it does not display any error msg.
public function insertFacturiFluxFurnizor(Request $request)
{
$user = auth()->user();
$idFluxReceptie = $request->input('idFluxReceptie');
$facturi = $request->input('facturi');
try {
foreach ($facturi as $factura) {
$facturiWms = FacturiWms::updateOrCreate([
'codFactura' => $factura['codFactura']
], [
'fluxReceptie' => $idFluxReceptie,
'idFurnizor' => $factura['idFurnizor'],
'fiscalId' => $factura['fiscalId'],
'codFactura' => $factura['codFactura'],
'dataFactura' => $factura['dataFactura'],
'userId' => $user->userId
]);
}
return response()->json(['facturiWms' => $facturiWms, 'message' => 'CREATED'], 201);
} catch (\Exception $e) {
return response()->json(['message' => $e], 409);
}
}
}
I'd like to know how I can populate the email_verified_at column with a timestamp upon the user clicking on the Verify Email Address contained in the verification email that's being sent.
I thought it'd be a straightforward thing to do hence my attempt below in the EmailVerificationController.php file but it didn't work.
What am I doing wrong and how can I fix it? Any feedback is appreciated :)
Here's api.php
Route::group(['middleware' => ['auth:sanctum', 'verified']], function () {
Route::post('email/verification-notification', [EmailVerificationController::class, 'sendVerificationEmail']);
Route::get('email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
$request->fulfill();
return redirect('/');
})->name('verification.verify');
});
Here's EmailVerificationController.php:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
class EmailVerificationController extends Controller
{
public function sendVerificationEmail(Request $request)
{
if ($request->user()->hasVerifiedEmail()) {
return [
'message' => 'Already Verified'
];
}
$request->user()->sendEmailVerificationNotification();
return ['status' => 'verification-link-sent'];
}
public function verify(EmailVerificationRequest $request)
{
if ($request->user()->hasVerifiedEmail()) {
return [
'message' => 'Email already verified'
];
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
$time = Carbon::now();
$timeStamp = $time->toDateTimeString();
User::create([
'email_verified_at' => $timeStamp
]);
}
return [
'message'=>'Email has been verified'
];
}
}
Here's AuthController.php
public function register(Request $request)
{
try {
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'age' => 'required',
'password' => 'required|min:6',
]);
$data = $request->all();
$dbData = [
'name' => $data['name'],
'email' => $data['email'],
'age' => $data['age'],
'password' => Hash::make($data['password'])
];
$user = User::create($dbData);
event(new Registered($user));
return response()->json([
"status" => true,
"message" => "Registered Successfully!",
'token' => $user->createToken('tokens')->plainTextToken
]);
} catch(\Exception $e) {
Log::error($e->getMessage());
throw new \Exception($e->getMessage(), $e->getCode(), $e);
}
}
You need to implement Laravel’s Must Verify Email feature in the API registration
Follow this tutorial
I am building registration form with Passport in Laravel using repository pattern, and when I try to register with postman I get error
Undefined property: Illuminate\\Http\\Response::$id
It breaks when I try and return response like this
return response(['user' => $user, 'access_token' => $accessToken]);
but when I just return $user instead then it works fine, but I don't have access token then. How can I register succesfully with access token? Any help is appreciated. Here is my code.
AuthController.php
public function register(RegisterUserRequest $request)
{
try {
$user = $this->service->createNewUser($request);
return $this->returnResource($user);
} catch (\Exception $exception) {
return $this->failureJson($exception);
}
}
AuthService.php
public function createNewUser(BaseRequest $request)
{
DB::beginTransaction();
try {
$request['confirmation_hash'] = Str::random(50);
$request['password'] = Hash::make($request['password']);
$user = parent::create($request);
Mail::to($user['email'])->send(new ConfirmationMail($user)); // Send email to user to confirm his email!
$accessToken = $user->createToken('authToken')->accessToken;
DB::commit();
return response(['user' => $user, 'access_token' => $accessToken]); // HERE IT BREAKS!!!
} catch (\Exception $exception) {
DB::rollBack();
throw new \Exception($exception->getMessage());
}
}
UserResource.php
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'password' => $this->password,
'remember_token' => $this->remember_token,
'api_token' => $this->api_token,
'confirmation_hash' => $this->confirmation_hash,
'email_verified_at' => $this->email_verified_at,
'is_verified' => $this->is_verified,
'verification_expires_at' => $this->verification_expires_at
];
}
Inside your createNewUser try to just return user return $user and then inside your UserResource.php create the token ' api_token' => $this->createToken('authToken')->accessToken
I tried to make auth API, I am success registed.
Than Signin can't success.
Please help me ,thanks.
public function login(Request $request)
{
try
{
if (!$request->has('Account')
|| !$request->has('Password'))
{
throw new Exception('Parameter missing');
}
$checkUser = DB::table('Users')->where('Account',$request->Account)->first();
if(empty($checkUser))
{
throw new Exception('No Data');
}
$data = ([
'Account' => $request->Account,
'Password' => $request->Password,
]);
if(!Auth::attempt($data))
throw new Exception('Verification error');
this db info.
Try following for register need to hash password before save in database:
User::create([
'Account' => $request->Account,
'CreateDateTime' => date('Y-m-d'),
'UpdatedDateTime' => date('Y-m-d'),
'Password' => Hash::make($request->Password),
]);
try this way it might helpful and evn ry validator also:
and if not sure about pass word then first debug
$table->string('password', 60)->nullable();
----------------------------------------------------
return Validator::make($data, [
'email' => 'required|email',
'password' => 'required',
]);
-----------------------------------------------
$user_data=User::where('username','=',$request->username)->first();
$userScope=$user_data->scope;
Input::merge([
'client_id' => env('CLIENT_ID'),
'client_secret' => env('CLIENT_SECRET'),
'scope' => 'admin'
]);
$credentials = $request->only(['grant_type', 'username', 'password','scope']);
$validationRules = $this->getLoginValidationRules();
$credentials["client_id"] = env('CLIENT_ID');
$credentials["client_secret"] = env('CLIENT_SECRET');
$this->validateOrFail($credentials, $validationRules);
try {
if (!$accessToken = Authorizer::issueAccessToken()) {
return $this->response->errorUnauthorized();
}
} catch (\League\OAuth2\Server\Exception\OAuthException $e) {
throw $e;
return $this->response->error('could_not_create_token', 500);
}
$accessToken["groups"][] = $userScope;
return response()->json(compact('accessToken'));
as this link and this link couldn't help me i'm wondering how can i validate unique mobile out of the user that is updating it on API level. for example:
public function register(Request $request)
{
try {
$user = User::whereMobileNumber($request->mobile_number)->first();
/*VALIDATION IF USER NOT FOUND*/
if ($user == null) {
$validator = Validator::make($request->all(), [
'mobile_number' => 'required|string|unique:users|min:11|max:11',
]);
}else{
/*VALIDATION IF USER HAVE DATA AND IGNORE CHECK MOBILE NUMBER*/
$validator = Validator::make($request->all(), [
'mobile_number' => 'required|string|min:11|max:11|unique:users,mobile_number,'.$user->mobile_number,
]);
}
if ($validator->fails()) {
return response(['data' => $validator->errors()->all(), 'status' => $user->mobile_number], 200);
}
...
} catch (\Exception $ex) {
return response(['data' => $ex->getMessage(), 'status' => '5'], 200);
}
}
unfortunately i get this error:
The mobile number has already been taken.
what happen in that and how can i resolve this problem?
You have to pass the user id not the phone number :
$validator = Validator::make($request->all(), [
'mobile_number' => 'required|string|min:11|max:11|unique:users,mobile_number,'.$user->id,
]);
Or you can use the laravel Rule class like this :
use Illuminate\Validation\Rule;
Validator::make($data, [
'mobile_number' => [
'required',mobile_number,
Rule::unique('users')->ignore($user->id),
],
]);