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'],
]);
}
}
Related
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"
I just implement the crud in my application And update api does not Working I don't know why. It is not throwing any error when I hit this api from postman.
public function update(int $id,Request $request)
{
// return $request->all();
$rules = [
'question' => 'required'
];
$validator = Validator::make(
$request->all(),
$rules
);
if ($validator->fails()) {
return response()->json(
[
__('messages.ERRORKEY') => $validator->errors(),
'message' => __('messages.VALIDATION_MESSAGE')
],
env('ERRORCODE', 422)
);
}
$question = Question::with('options')->find($id);
$question->update(['question' => $request->question]);
return response()->json([
"success" => true,
"message" => "Question saved successfully.",
"data" => $question
]);
}
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' => []]);
}
}
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
I am using token guard to authenticate users using api_token passed in post request. But I am unable to retrieve api_token using token guard guard. I thought of getting user from retrieveByCredentials($credentials) and check for password using validateCredentials($user, $credentials) which are in EloquentUserProvider.php, but to access them I have to use Auth::guard('api')->provider where provider is a protected property. So I have to manually do that. Is there any simple procedure to get the api_token when login is implemented.
My login method in AuthController.php
public function api_login(Request $request)
{
$validator = Validator::make($request->all(), ['email' => 'required', 'password' => 'required']);
$credentials = $this->getCredentials($request);
$user = Auth::guard('api')->provider->retrieveByCredentials($credentials);
if(is_null($user)) {
return response()->json([
'error' => [
'message' => 'Your email is not registered yet',
'status_code' => 40
]
]);
} elseif(Auth::guard('api')->provider->validateCredentials($user, $credentials)) {
return response()->json([
'success' => [
'api_token' => Auth::guard('api')->user()->api_token,
'message' => 'Login successful',
'status_code' => 200
]
]);
}
return response()->json([
'error' => [
'message' => 'Login failed',
'status_code' => 20
]
]);
}
Note: I used provider, but I can't use that as it is a protected property.
In Laravel 5.2, there are 2 authentication guard 'web' and 'api', they are implemented in SessionGuard and TokenGuard respectively, as you know.
TokenGuard doesn't have modules for checking validation with email and password, it only checks validity using api_token.
But SessionGuard does; attempt() method.
So we can use web guard for login only, and can use 'auth:api' middleware for the other apis.
Here is login function, which can be implemented easily.
public function api_login(Request $request)
{
$validator = Validator::make($request->all(), ['email' => 'required', 'password' => 'required']);
$credentials = $this->getCredentials($request);
// only web guard can validate with credentials
$guard = Auth::guard('web');
if ($guard->attempt($credentials)) {
// maybe you can generate api_token again here
return response()->json([
'success' => [
'api_token' => $guard->user()->api_token,
'message' => 'Login successful',
'status_code' => 200
]
]);
}
else {
return response()->json([
'error' => [
'message' => 'Login failed',
'status_code' => 200
]
]);
}
}