Postman failing to send json to PHP api - php

public function register(Request $request) {
// $user = User::create([
// 'name' => $request->input('name'),
// 'email' => $request->input('email'),
// 'password' => Hash::make($request->input('password'))
// ]);
//
// return $user;
return "test";
}
Hi all,
basically, I'm trying to build a restful API with Laravel and my API is being hit by Postman, but when I send a JSON body my $request is an empty array.
It's the first time I'm touching Laravel so it's probably something obvious so thank you in advance !

Try this one
use Exception;
public function register(Request $request) {
try {
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => Hash::make($request->input('password'))
]);
return response()->json(['status' => true, 'message' => 'You have been register successfully', 'data' => $user]);
} catch (Exception $e) {
return response()->json(['status' => false, 'message' => $e->getMessage(), 'data' => []]);
}
}

Related

Method for validating request in BaseController in Laravel for APIs

I've been trying to create a method in BaseController.php for validating requests in laravel for APIs. If I use the $this->validate($request, $rules) in API controller it doesn't return the required result. I used this code initially.
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'phoneNo' => "required|max:15|min:11|unique:users,phoneNo",
'username' => 'required|unique:users,username',
'password' => 'required',
'c_password' => 'required|same:password'
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors());
}
But I don't want to do this for every method in every controller.
So, I thought that instead of writing this in every controller I should create a method in BaseController.php which I can use in every controller as all controllers are inherited from the BaseController.php.
So, I wrote this to achieve the functionality but this isn't working as it should.
class BaseController extends Controller
{
/**
* success response method.
*
* #return \Illuminate\Http\Response
*/
public function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
/**
* return error response.
*
* #return \Illuminate\Http\Response
*/
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
'success' => false,
'message' => $error,
];
if (!empty($errorMessages)) {
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
public function validateRequest($request, $rules)
{
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) return $this->sendError("Validation Error.", $validator->errors());
}
}
And in the register controller I use this
$this->validateRequest($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'phoneNo' => "required|max:15|min:11|unique:users,phoneNo",
'username' => 'required|unique:users,username',
'password' => 'required',
'c_password' => 'required|same:password',
]);
but it doesn't return an exception here. So, I have to add return to this statement in order for it to return an error. but it should stop the process itself and return the response to API here.
Any help would be appreciated.
Thank you
Update
I found the answer to it. I was a little wrong about this. I forgot to add Accept: "application/json" parameter in the header. We can simply use the same old validation method:
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users,email',
'phoneNo' => "required|max:15|min:11|unique:users,phoneNo",
'username' => 'required|unique:users,username',
'password' => 'required',
'c_password' => 'required|same:password',
]);
If you are working with API and you want to show a JSON response to this then, you can simply add this in your request headers and it will return a proper JSON response:
Accept: "application/json"

Laravel passport: Lcobucci\JWT\Token\InvalidTokenStructure Value is not in the allowed date format

I created a laravel passport to authenticate apps via an api. The setup works local on my machine very well, but when I move the project to the server, I always get the following error:
"Lcobucci\JWT\Token\InvalidTokenStructure
Value is not in the allowed date format: 1616443683.7318161"
The user gets created and the registration throws an error 500 in the following line:
$success['token'] = $user->createToken('appToken')->accessToken;
Registration function
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'firstname' => 'required',
'lastname' => 'required',
'phone' => 'digits_between:4,30|numeric',
'email' => 'required|email|unique:users',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'message' => $validator->errors(),
], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('appToken')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
}
Downgrade Lcobucci\JWT from latest to v3.4

Laravel response is the homepage on controller update method

I'm facing a stange behavior when I call this controller method from a Guzzle PUT on another app, Laravel response is the homepage with or without validation rules
public function update(Request $request, Stage $stage)
{
$jsonRequest = json_decode($request->all()[0]);
/*return response()->json([
'request' => $jsonRequest
]);*/
/*$validatedData = $request->validate([
'id'=>'required'
]);*/
if($stage->update($jsonRequest)){
return response()->json([
'result' => 'success',
'id' => $request->get('id'),
]);
}else{
return response()->json([
'result' => 'error',
'id' => $request->get('id'),
]);
}
}
I've checked the request is sended but I'm unable to update and having the exepected response.
OK i've found the problem json_decode must use the associative parameter to return an array
like that
public function update(Request $request, Stage $stage)
{
$RequestArray = json_decode($request->all()[0],true);
/*return response()->json([
'request' => $jsonRequest
]);*/
/*$validatedData = $request->validate([
'id'=>'required'
]);*/
if($stage->update($RequestArray)){
return response()->json([
'result' => 'success',
'id' => $RequestArray['id'],
]);
}else{
return response()->json([
'result' => 'error',
'id' => $RequestArray['id'],
]);
}
}

Where am I going wrong when creating authentication in Laravel?

PHP 7.4
Laravel 8
Route 1 (super.com/auth):
Receives email, password data and makes authentication.
$result = Auth::Attempt(['password' => 'superpwd', 'email' => 'super#mail.ru'], true);
Auth::check() // true
Route 2 (super.com/testAuthCheck):
We check the authentication.
Auth::check(); // false
It turns out that the authentication is not saved in the session.
Please tell me where I'm wrong? May be session or some setting, or modules...
Full code:
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Hash;
class AuthUser extends Controller
{
public function register(Request $request)
{
$request->validate([
'name' => 'required|string',
'lastname' => 'required|string',
'secondname' => 'required|string',
'tel' => 'required|numeric',
'password' => 'required|string',
]);
$user = User::create([
'name' => $request->name,
'lastname' => $request->lastname,
'secondname' => $request->secondname,
'tel' => $request->tel,
'password' => Hash::make($request->password),
'email' => '',
]);
$login = Auth::login($user);
return response()->json([
'message' => 'Success!',
'login' => $login
]);
}
public function test(Request $request) {
if(Auth::Attempt(['password' => 111, 'email' => 'a#b.ru'], true)) {
$request->session()->regenerate();
$result = Auth::check();
dump($result); // true
}
}
public function test2(Request $request) {
$result = Auth::check();
dump($result); // false
}
Using dump will most likely cause more problems while debugging this.
public function test(Request $request) {
if(Auth::Attempt(['password' => 111, 'email' => 'a#b.ru'], true)) {
$request->session()->regenerate();
$result = Auth::check();
//dump($result); ***will terminate the request and the session will not be set correctly ***
info($result); // check storage/logs/laravel.log
}
}

Authenticate users without email in Laravel

I'm trying to make email optional when user signs up. Here is package. So I removed email' => 'required|email|unique:users', in this function:
public function signup(Request $request)
{
$credentials = $request->all();
$validator = Validator::make($credentials, [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:3'
]);
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) {
return $this->login($request);
}
return $this->response->created();
} catch (\Exception $e) {
return $this->response->error($e->getMessage(), 500);
}
}
then in config-boilerplate.php I also removed email:
'signup_fields_rules' => [
'name' => 'required',
'email' => 'required|email|unique:users',///// this
'password' => 'required|min:6'
],
But when I sign up I get this error :
"message": "Undefined index: email",
"status_code": 500,
"debug": {
"line": 173,
"file": "/Users/MyMac/Desktop/Project/laravel-5.3-boilerplate-api-jwt-vue2/vendor/dingo/api/src/Http/Response/Factory.php",
"class": "Symfony\Component\HttpKernel\Exception\HttpException",
the route:
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->post('auth/signup', 'App\Api\V1\Controllers\AuthController#signup');
Is there anything I need to disable to allow users sign-up with or without email ?
If you want to make email as optional field, just use sometimes|email See Docs. Try below code:
public function signup(Request $request)
{
$credentials = $request->all();
$validator = Validator::make($credentials, [
'name' => 'required',
'email' => 'sometimes|email',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:3'
]);
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) {
return $this->login($request);
}
return $this->response->created();
} catch (\Exception $e) {
return $this->response->error($e->getMessage(), 500);
}
}
config-boilerplate.php
'signup_fields_rules' => [
'name' => 'required',
'email' => 'sometimes|email',///// this
'password' => 'required|min:6'
],

Categories