How to solve 422 error in Lumen react Post request? - php

I am new in Lumen also in React, so i don't know what is going wrong with my code it return the error like below, I am using axios library. It works fine in postman
Here is my react code
handleFormSubmit = (event) => {
event.preventDefault();
const data = {
name: this.state.name,
email: this.state.email,
password: this.state.password
}
// Axios.post('http://localhost:8000/api/register', data).then(res => {
// console.log(res);
// })
fetch('http://localhost:8000/api/register', {
method: 'POST',
body: data
}).then(res => {
console.log(res);
});
}
Lumen Code
public function register(Request $request)
{
$rules = [
'email' => 'required|email|unique:users',
'name' => 'required|min:5',
'password' => 'required|min:6'
];
$this->validate($request, $rules);
$name = $request->input('name');
$email = $request->input('email');
$password = $request->input('password');
$hashPassword = Hash::make($password);
$user = User::create([
'email' => $email,
'name' => $name,
'password' => $hashPassword
]);
return response()->json(['status' => 'success', 'user_id' => $user->id], 201);
}
Any solution appreciated!

Related

Why's my POST request turning into a GET request upon submitting the form?

I'm using a Laravel (8) backend with a React.js frontend. In my code, I'm making a POST request to my server. The data gets successfully sent to the database but I'm not getting a response in the console.
Instead, it's somehow turning the POST request into a GET request and I have no clue why. The reason why I know it's turning into a GET request's because I see the params in the URL upon submitting the form as well as verifying through the Network tab.
I've been trying to debug for this days on end but nothing seems to work - I've tried everything under the sun and all suggestions in SO to resolve this but to no avail. What am I doing wrong?
React.js code:
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const handleSubmit = () => {
let data = {
'name': name,
'email': email,
'password': password,
'c_password': confirmPassword
};
JSON.stringify(data);
axios.post('http://website.test/api/register', data)
.then(resp => {
console.log(resp);
}).catch(error => {
console.log(error);
});
}
api.php:
Route::middleware(['cors'])->group(function () {
Route::post('/register', [RegisterController::class, 'register']);
});
RegisterController.php:
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors());
}
$userId = 'u-' . Str::uuid()->toString();
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$input['UserID'] = $userId;
$user = User::create($input);
$input['name'] = $user->name;
$success['token'] = $user->createToken('MyApp')->accessToken;
return $this->sendResponse($success, 'User registered successfully.', $input['UserID']);
}
cors.php
return [
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
I don't know what your form looks like how you are triggering the submit, but my best guess is you are triggering the default form submit action, which is a GET request.
You need to prevent the form from doing that by adding event.preventDefault(); at the top of your submit handler.

How am I authenticated in the front end but not authenticated when checking for it in my controller?

It keeps giving failed via my controller when trying to make the post request. I'm trying to make a file upload and storing that file name associated with the user into my db. I'm not sure what I'm doing wrong here, I've tried many ways to fix this but to no avail as I've hit a wall. I believe it may be the way my code's written in my controller but I'm not too sure.
The error I'm getting in the logs is Call to a member function photos() on null which means
auth()->user() is not detecting the authenticated user and there lies the problem which begs the question - how? I'm logged in using correct credentials without issues. How come I can't validate in a separate controller?
What am I doing wrong and how can I fix this?
Note: My React.js and Laravel code bases are separated.
Here's my react form submission:
handleSubmit(e) {
e.preventDefault();
console.log("here in submitHandler()");
let access_token = Cookies.get("access_token").slice(13, -8);
const headers = {
Authorization: `Bearer ${access_token}`
}
console.log(this.state.file_path);
axios.post('http://myendpoint/api/auth/dashboard', this.state.file_path, {headers})
.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
})
};
Here's my FileUploadController.php:
public function uploadTest(Request $request) {
if(auth()->user()) {
auth()->user()->photos()->create([
'file_path' => $request->file('fileToUpload')->getClientOriginalExtension()
]);
return response()->json($request->session()->get("user"));
}
return "failed";
}
Here's my User model:
public function photos() {
return $this->hasMany(Photo::class);
}
Here's my Photo model:
public function user() {
return $this->belongsTo(User::class);
}
Here's my auth for creating user and logging in (AuthController.php):
public function signup(Request $request) {
$request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed'
]);
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$user->save();
return response()->json([
'message' => 'Successfully created user!'
], 201);
}
public function login(Request $request) {
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
$request->session()->put("user", $user);
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString(),
$user
]);
}

Undefined variable in Lumen

I am going to send email using gmail smtp in lumen, Everything working fine but one variable is always undefined, Please let me know where i am wrong
Here is my code
<?php
namespace App\Services;
use Illuminate\Support\Facades\Mail;
class MailService
{
public static function send($mail_to = '', $title = '', $content = '') {
Mail::send('mail', ['title' => $title, 'content' => $content], function ($message) {
$message->from('noreply#gmail.com', 'Test Mail');
$message->to($mail_to);
});
}
}
Here is the Controller
public function register(Request $request)
{
$rules = [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:5',
'phone' => 'required|numeric|min:10',
'business_name' => 'required|unique:users',
'business_type' => 'required'
];
$this->validate($request, $rules);
$data = $request->all();
$hashPassword = Hash::make($data['password']);
$data['password'] = $hashPassword;
$data['is_activated'] = 'false';
$pin = mt_rand(1000, 9999);
$token = hash("sha256", $pin);
$data['token'] = $token;
$data['otp'] = $pin;
$user = User::create($data);
if ($user) {
MailService::send($request->input('email'), 'OTP', $pin);
return response()->json(['response' => true, 'message' => 'User registered Successfully', 'token' => $token], 201);
} else {
return response()->json(['response' => false, 'message' => ' Please check your credentials, Try again'], 400);
}
}
Here is the error
{message: "Undefined variable: mail_to", exception: "ErrorException", file: "D:\xampp\htdocs\api\app\Services\MailService.php", line: 12, trace: Array(28)}
exception: "ErrorException"
file: "D:\xampp\htdocs\api\app\Services\MailService.php"
line: 12
message: "Undefined variable: mail_to"
You are missing $mail_to. you need to use it in function then you may use it otherwise you would get an undefined variable error as you're getting it now.
use($mail_to)
Here your code looks like below.
public static function send($mail_to = '', $title = '', $content = '') {
Mail::send('mail', ['title' => $title, 'content' => $content], function ($message) use($mail_to) {
$message->from('noreply#gmail.com', 'Test Mail');
$message->to($mail_to);
});
}

Laravel 5.7 auth can't get success

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'));

i want to register user in laravel 5.2 by ajax, but the image file always turn null, why?

my ajax code is:
$('form.employeeForm').on('submit',function(){
$("span").hide();
$(".danger").removeClass("danger");
var that=$(this),
url=that.attr('action'),
method=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){
var that=$(this),
name=that.attr('name'),
value=that.val();
data[name]=value;
});
console.log(data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': data['_token']
}
});
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: data,
beforeSend: function () {
$('#addEmployee').val('Recording data..........');
},
complete: function () {
$('#addEmployee').val('Save Record');
},
success: function (data) {
console.log(data);
},
error: function(data){
var errors= data.responseJSON;
//var error=errors.name[0];
$.each(errors.errors, function(key, value) {
console.log(key,value);
//$('input','textarea').removeClass('error');
var dtextarea=$('textarea[name="'+key+'"]').closest('textarea[name="'+key+'"]');
dtextarea.next('.text-danger').remove();
dtextarea.addClass('danger').after("<span class='text-danger'>"+value+"<br></span>");
var dinput=$('input[name="'+key+'"]').closest('input[name="'+key+'"]');
dinput.next('.text-danger').remove();
dinput.addClass('danger').after("<span class='text-danger'>"+value+"<br></span>");
//$('input[name="'+key+'"]').addClass('danger').closest('input[name="'+key+'"]').after("<span class='text-danger'>"+value+"</span>");
});
}
});
return false;
});
Controller Code is:
public function eregister(Request $request){
if ($request->ajax()) {
$rules = [
'full_name' => 'required',
'image' => 'required',
'eid' => 'required',
'username' => 'required',
'address' => 'required',
'join_date' => 'required',
'n_id_no' => 'required',
'position' => 'required',
'blood' => 'required',
'birth_date' => 'required',
// 'role' => 'required',
'phone_no' => 'required',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed',
'password_confirmation' => 'required|min:6',
];
$validation = Validator::make($request->all(), $rules);
$errors=$validation->errors();
//print_r($errors->image);
if ($validation->fails()) {
return response()->json([
'status' => 'false',
'errors' =>$validation->errors()], 400);
//return response()->json($validation->errors());
} else {
$uploadDirectory = 'uploads/';
$file = $request->file('image');
$filename = $request->input('username') . "." . $file- >getClientOriginalName();
$saveData = new User();
if ($file->move($uploadDirectory, $filename)) {
$saveData->image = $filename;
$saveData->position = $request->input('position');
$saveData->full_name = $request->input('full_name');
$saveData->eid = $request->input('eid');
$saveData->phone_no = $request->input('phone_no');
$saveData->username = $request->input('username');
$saveData->address = $request->input('address');
$saveData->join_date = $request->input('join_date');
$saveData->n_id_no = $request->input('n_id_no');
$saveData->email = $request->input('email');
$saveData->blood = $request->input('blood');
$saveData->birth_date = $request->input('birth_date');
$saveData->status =1;
$saveData->password = Hash::make($request->input('password'));
if($saveData->save()){
return response()->json([
'status' => 'true',
'errors' =>null], 200);
}
}
}
} else {
return view('auth.register');
}
}
The problem is it always fires the error block of ajax though the form validation succeeded. I have debug the response of ajax for a validate form it returns 500 on network tab and the reason is the $file variable got null though i select an image file.

Categories