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
]);
}
Related
I've been researching for all internet why do I get this error when I try to POST on the login api route:
Status 419
unknown status
Version HTTP/1.1
Transferred 6.94 KB (6.46 KB size)
Referrer Policy strict-origin-when-cross-origin
This is what I have on my UserController.php:
public function userSignUp(Request $request) {
$validator = Validator::make($request->all(), [
"name" => "required",
"email" => "required|email",
"password" => "required",
]);
if($validator->fails()) {
return response()->json(["status" => "failed", "message" => "validation_error", "errors" => $validator->errors()]);
}
$userDataArray = array(
"name" => $request->name,
"email" => $request->email,
"password" => md5($request->password),
);
$user_status = User::where("email", $request->email)->first();
if(!is_null($user_status)) {
return response()->json(["status" => "failed", "success" => false, "message" => "Ooops! Email ya registrado anteriormente"]);
}
$user = User::create($userDataArray);
if(!is_null($user)) {
return response()->json(["status" => $this->status_code, "success" => true, "message" => "Registro completado correctamente", "data" => $user]);
}
else {
return response()->json(["status" => "failed", "success" => false, "message" => "Fallo al registrar"]);
}
}
// ------------ [ User Login ] -------------------
public function userLogin(Request $request) {
$attr = $request->validate([
'email' => 'required|string|email|',
'password' => 'required|string|min:6'
]);
if (!Auth::attempt($attr)) {
return response()->json([
'message' => 'Invalid login details'
], 401);
}
$token = auth()->user()->createToken('auth_token')->plainTextToken;
$user = auth()->user();
$respon = [
'status' => 'success',
'msg' => 'Login successfully',
'content' => [
'status_code' => 200,
'access_token' => $token,
'token_type' => 'Bearer',
'user_name' => $user->name,
'user_email' => $user->email,
'user_id' => $user->id,
]
];
return response()->json($respon, 200);
}
And I have these routes on api.php:
Route::post("login", [UserController::class, "userLogin"]);
Route::post("register", [UserController::class, "userSignUp"]);
These routes works perfectly on the RESTED add-on on Firefox. This is on api.php, I shouldn't have any problem with csrf token.
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 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'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'],
]);
}
}
I have a very strange bug.
Running Laravel 4.1 as my company hasn't upgraded their PHP version yet.
The routes file has this:
Route::controller('survey', 'SurveyController');
And, when you go to /survey/new-survey it ends up being sent to postNewQuestion function instead of postNewSurvey.
public function postNewSurvey() {
$input = Input::all();
//dd($input);
$rules = array(
'name' => 'required|unique:lime_surveys_languagesettings,surveyls_title',
'language' => 'required'
);
...... etc
}
public function postNewQuestion() {
$input = Input::all();
//dd($input);
$rules = array(
'sid' => 'required',
'gid' => 'required',
'type' => 'required',
'question' => 'required',
'mandatory' => 'required',
);
$validator = Validator::make($input, $rules);
if($validator->fails()) {
return Response::json(array('success' => false, 'error' => 'validation',
'messages' => $validator->messages(), 'failed' => $validator->failed()));
}
......... etc
}
Thanks.