How can i pass only one message for all fields - laravel

This is code of register function which generate error of success and failure.
public function register(Request $request) {
$validator = Validator::make($request->all(),
[
'user_type' => 'required',
'fname' => 'required',
'lname' => 'required',
'dob' => 'required',
'phone' => 'required',
'gender' => 'required',
'uname' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['failed'=>$validator->errors()], 401); }
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('AppName')->accessToken;
$success['status'] = true;
$success['data'] = [$user];
$success['message'] ="User created successfully!";
// return response()->json([
// "message" => " record created"
// ], 201);
return response()->json($success, $this->successStatus);
}
This is my output
1.All error message show in one line..This is my main point..But i want to actually this message of This image...How can i do that?
2.Second thing in API if any user put same email id api give json error not laravel error..

Try this:
return response()->json(['status'=> False, 'msg' => 'This is not successful'], 401);
You can pass custom json in response instead of validator response.
For checking if email exists update the validation like this:
'email' => 'required|email|unique:users,email',
where users is your table name and email is your column name

You just need to replace your code
if ($validator->fails()) {
return response()->json(['failed'=>$validator->errors()], 401);
with
if ($validator->fails()) {
return response()->json(['status'=> 'False', 'msg' => 'This is not sccessfully'], 401);

Related

Sending custom verification emails from a controller method

I have some data i am receiving from new users and extracting the email to send to the new user. This is how i am doing it
public function register_mechanic_post(Request $request)
{
$validatedData = $request->validate([
'email' => 'required|email|unique:users',
'password' => 'required',
'password_confirmation' => 'required'
], [
'email.required' => 'Email address is required',
'password.required' => 'Password field is required',
'password_confirmation.required' => 'Password confirmation field is required'
]);
$data = $request->all();
$name = $request->input('name');
$data['role'] = 'manager';
$email = $request->input('email');
User::create([
'email' => $request->input('email'),
'name' => $request->input('name'),
'role' => 'manager',
'password' => Hash::make($request->input('password')),
//'email_verified_at' => now()
]);
$user = User::where('email','=',$email)->first();
$user->sendEmailVerificationNotification();
return back()->with('success', 'Mechanic created successfully.');
}
I am getting this error
403 THIS ACTION IS UNAUTHORIZED
The docs say its because of signed urls https://laravel.com/docs/9.x/urls#signed-urls
I haven't modified the existing email verification code as shipped with laravel. How do i use the signed urls feature in my case?.
Not an answer, but your code could be significantly simpler, making it easier to manage in the future.
public function register_mechanic_post(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
'password_confirmation' => 'required'
], [
'email.required' => 'Email address is required',
'password.required' => 'Password field is required',
'password_confirmation.required' => 'Password confirmation field is required'
]);
$user = User::create([
'email' => $validatedData['email'],
'name' => $validatedData['name'],
'role' => 'manager',
'password' => Hash::make($validatedData['password']),
'email_verified_at' => now()
]);
$user->sendEmailVerificationNotification();
return back()->with('success', 'Mechanic created successfully.');
}
But why ask the user to verify their email when you are already setting the email_verified_at timestamp (indicating that verification has been performed)

custom validation message in laravel 8

how to give custom laravel message in my coding i am new in laravel
$validatedData = $r->validate([
'preference' => 'required',
'objective_1' => 'required',
'objective_2' => 'required',
'objective_5' => 'required',
]);
if (empty($r->session()->get('sessForm'))) {
$r->session()->put('sessForm', $validatedData);
} else {
$sessForm = $r->session()->get('sessForm');
$r->session()->put('sessForm', $sessForm);
}
You can use custom validator. Check the documentation. You can get messages from $errors variable in blade template.
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
], [
'title.required' => 'Title required custom message',
'title.unique' => 'Title unique custom message',
// ...
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
If you want to send redirect with data. You can use
redirect()->route('route')->with('data', 'test');
You can get after redirect
session('data')

Laravel 8: How to send validation response in JSON format using postman

I have this validation, how can I return an error response in postman?
please help guys.
$rules = [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
];
$validator = $this->validate($request, $rules);
$data = $request->all();
use Illuminate\Support\Facades\Validator;
Then write validation like
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
]);
if ($validator->fails()) {
return response()->json([
'message' => 'Invalid params passed', // the ,message you want to show
'errors' => $validator->errors()
], 422);
}

Auth::attempt value always false

I have some problem when I want to make login, I got an issue for my Auth::attempt always false value, Is am I got something wrong in my code?
Controller :
public function register(Request $register)
{
$validator = Validator::make($register->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
} else {
$name = $register->input('name');
$email = $register->input('email');
$pwd = $register->input('password');
$c_pwd = $register->input('c_password');
// Crypting password & c_password to md5
$md5_pwd = md5($pwd);
$md5_c_pwd = md5($c_pwd);
// Salt password & c_password
$password = crypt($md5_pwd, "asd");
$c_password = crypt($md5_c_pwd, "asd");
$data = new User();
if ($password == $c_password) {
$user = User::create([
'name' => $name,
'email' => $email,
'password' => $password,
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json(['error' => "Password doesn't match"], 401);
}
}
}
public function login()
{
$email = request('email');
$pwd = request('password');
$md5 = md5($pwd);
$password = crypt($md5, "asd");
if (Auth::attempt(['email' => $email, 'password' => $password])) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
}
I assume you messed up with Laravel Default Password Hashing System
public function register(Request $register)
{
$validator = Validator::make($register->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
} else {
$name = $register->input('name');
$email = $register->input('email');
$pwd = $register->input('password');
$c_pwd = $register->input('c_password');
// $data = new User();
$user = User::create([
'name' => $name,
'email' => $email,
'password' => bcrypt($password . 'salt'),
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
}
}
public function login()
{
$email = request('email');
$pwd = request('password');
if (Auth::attempt(['email' => $email, 'password' => $password . 'salt'])) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
}
Try this code. I don't know what happened to your code about the password you tried to encrypt it in attempt.
public function login(LoginRequest $request) {
if(!Auth::attempt([
'email' => $request->email,
'password' => $request->password,
'active' => true
])) {
return response()->json('Email or Password is incorrect', 500);
}
$this->user = Auth::user()->load('roles');
return $this->createUserAccessTokenResponse();
}
protected function createUserAccessTokenResponse() {
return response()->json([
'status' => 'success',
'data' => [
'token' => $this->user->createToken($this->user->name)->accessToken,
'user' => $this->user
],
], 200);
}
your problem is that laravel by default hashes the password. so when you do Auth::attempt it's going to hash the password you provided. And the result is what you get, it will always false.
Instead, you need to Other Authentication Methods.
Auth::login($user);
// Login and "remember" the given user...
Auth::login($user, true);
Above is the easiest way to fix your code.
It's recommended to hash your password rather than encrypting the password.
Hashing password in laravel is also
Hash::make($password);
And then you can use Auth::attempt to log in your user.
Laravel Auth uses the bcrypt hashing when saving password via model you may use either of the 2 method
$account->password = bcrypt("YOUR_PASSWORD"); or $account->password = Hash::make("YOUR_PASSWORD");
Then if you're dealing with the auth attempt function, just simply call the method like this
if($account = Auth::attemp(['email' => "YOUR_EMAIL#DOMAIN.COM", 'password' => "YOUR_PASSWORD"])){
//success login, do your extra job here
}else{
//invalid credentials here
}
Instead of using md5 or crypt use \Hash::make() it is much secure
I refactored your code and it does the same thing
You only need to rename your c_password to password_confirmation
Source
Below code does the same thing that your code do
public function register(Request $register)
{
$this->validate($register, [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
$user = User::create([
'name' => $register->input('name'),
'email' => $register->input('email'),
'password' => $register->input('password'),
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user,
]);
}
public function login(Request $request)
{
$request->merge(['password' => \Hash::make($request->input('password'))]);
if (Auth::attempt($request->only(['email', 'password']))) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user,
]);
}
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
when you hashing password using crypt it has a key to unlock it that's why there is a decrypt but when you use Hash::make() it doesn't have a key to break or unlock it, it will check it's algorithm to see if given password is matching the algorithm that already exists in the database that's why crypt is not safe and Hash::make is much much more safe

Laravel 5.3 OAuth token error in REST API

When I am trying to register a user from mobile, that data is inserting in the users table but not in oauth_clients. It should upload at the same time.
When I try to login, it shows oauth/token 401 error
Here are my routes:
Route::post('/register' , 'ProviderAuth\TokenController#register');
Route::post('/oauth/token' , 'ProviderAuth\TokenController#authenticate');
This is my register function, which is in TokenConrtoller:
public function register(Request $request)
{
$this->validate($request, [
'device_id' => 'required',
'device_type' => 'required|in:android,ios',
'device_token' => 'required',
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:providers',
'mobile' => 'required',
'password' => 'required|min:6|confirmed',
]);
try{
$Provider = $request->all();
$Provider['password'] = bcrypt($request->password);
$Provider['status'] = 'approved';
$Provider = Provider::create($Provider);
ProviderDevice::create([
'provider_id' => $Provider->id,
'udid' => $request->device_id,
'token' => $request->device_token,
'type' => $request->device_type,
]);
return $Provider;
} catch (QueryException $e) {
if ($request->ajax() || $request->wantsJson()) {
return response()->json(['error' => 'Something went wrong, Please try again later!'], 500);
}
return abort(500);
}
}
This is my authenticate method:
public function authenticate(Request $request)
{
$this->validate($request, [
'device_id' => 'required',
'device_type' => 'required|in:android,ios',
'device_token' => 'required',
'email' => 'required|email',
'password' => 'required|min:6',
]);
Config::set('auth.providers.users.model', 'App\Provider');
$credentials = $request->only('email', 'password');
try {
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'The email address or password you entered is incorrect.'], 401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'Something went wrong, Please try again later!'], 500);
}
$User = Provider::with('service', 'device')->find(Auth::user()->id);
$User->access_token = $token;
$User->currency = Setting::get('currency', '$');
if($User->device) {
if($User->device->token != $request->token) {
$User->device->update([
'udid' => $request->device_id,
'token' => $request->device_token,
'type' => $request->device_type,
]);
}
} else {
ProviderDevice::create([
'provider_id' => $User->id,
'udid' => $request->device_id,
'token' => $request->device_token,
'type' => $request->device_type,
]);
}
return response()->json($User);
}
I think you should register in JWT auth Like
$token = JWTAuth::fromUser($user);
after Register User
Check this Link for more information
https://blog.pusher.com/laravel-jwt/

Resources