hello I have a problem with the password field to create a user in laravel for a restfullapi
public function store(Request $request)
{
$this->validate($request,[
'user_names' => 'required||string|max:45',
'user_lastnames' => 'required|string|max:45',
'user_email' => 'required|string|email|unique:users,user_email|max:150',
'user_password' => 'required|string|min:6|confirmed',
'user_password_confirmation' => 'required|min:6',
'user_gender' => 'required',
'user_celphone' => 'required|numeric',
'user_origin_country' => 'required|string|max:100',
]);
$user_names = $request->input('user_names');
$user_lastnames = $request->input('user_lastnames');
$user_email = $request->input('user_email');
$user_password = $request->input('user_password');
$user_password_confirmation = $request->input('user_password_confirmation');
$user_gender = $request->input('user_gender');
$user_celphone = $request->input('user_celphone');
$user_origin_country = $request->input('user_origin_country');
$user = new User([
'user_names' => $user_names,
'user_lastnames' => $user_lastnames,
'user_email' => $user_email,
'user_password' => bcrypt($user_password),
'user_gender' => $user_gender,
'user_celphone' => $user_celphone,
'user_origin_country' => $user_origin_country
]);
$credentials = [
'user_email' => $user_email,
'user_password' => $user_password
];
if ($user->save()) {
$token = null;
try {
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json([
'error' => 'El email ó la contraseña son incorrectos'
],404);
}
} catch (JWTAuthException $e) {
return response()->json([
'error' => 'failed_to_create_token',
],404);
}
$user->signin = [
'href' => 'api/v1/user/signin',
'method' => 'POST',
'params' => 'user_email, user_password'
];
$response = [
'success' => 'Usuario creado exitosamente',
'Usuario' => $user,
'token' => $token
];
return response()->json($response, 201);
}
$response = [
'error' => 'Ha ocurrido un error'
];
return response()->json($response,404);
}
I'm testing the application with postman and he tells me this
postman's picture
I have verified the routes and it works, before placing the jwt I saved the data in the db without password problems, thanks in advance
Related
I am trying to insert some record by checking if certain conditions are met. What I am planning to do is to restrict the users from voting twice daily. I am using email and date as parameters.
public function store(Request $request)
{
$this->validate($request, [
'flavour' => 'required|string',
'email' => 'required|email',
'lastname'=> 'required|string',
'firstname' => 'required|string'
]);
$vote = new Vote();
//$currentDate = Carbon::now()->toDateString();
$today = Carbon::now()->format('Y-M-D');
$dup = Vote::where(['email' => $request->email, 'created_at' => $today ])->get();
if (!$dup)
{
$vote->firstname = $request->firstname;
$vote->lastname = $request->lastname;
$vote->email = $request->email;
$vote->flavour = $request->flavour;
$vote->voter_ip = $request->ip();
}
else {
return response()->json([
'message' => 'You have voted today, please wait till another day!'
]);
}
if (auth()->user()->votes()->save($vote))
return response()->json([
'success' => true,
'data' => $vote->toArray()
]);
else
return response()->json([
'success' => false,
'message' => 'Vote could not be added'
], 500);
}
The problem I am encountering now is, it doesn't take any record as it keeps displaying the message "You have voted today, please wait till another day", even if I insert a new email and/or a current user with different emails.
First, I had to create a field in my migration called "voted_at" and rearranged the code to check for the existing record based on the voted_at and email of the user
public function store(Request $request)
{
$this->validate($request, [
'flavour' => 'required|string',
'email' => 'required|email',
'lastname'=> 'required|string',
'firstname' => 'required|string'
]);
$today = Carbon::now()->toDateString();
$dup = Vote::where(['email' => $request->email, 'voted_at' => $today ])->exists();
if ($dup){
return response()->json([
'data' => $dup,
'message' => 'You have voted today, please wait till another day!'
]);
}
else {
$vote = new Vote();
$vote->firstname = $request->firstname;
$vote->lastname = $request->lastname;
$vote->email = $request->email;
$vote->flavour = $request->flavour;
$vote->voter_ip = $request->ip();
$vote->voted_at = $today;
if (auth()->user()->votes()->save($vote))
return response()->json([
'success' => true,
'data' => $vote->toArray()
]);
else
return response()->json([
'success' => false,
'message' => 'Vote could not be added'
], 500);
}
}
Thanks
I'm trying to make a login from another model and I have an error.
This is my code for Student Model
var $name= 'Student';
public $components = array(
'Session',
'Auth' => array(
'loginAction' => array(
'controller' => 'students',
'action' => 'login',
'plugin' => 'students'
),
'authError' => 'Did you really think you are allowed to see that?',
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'username', //Default is 'username' in the userModel
'password' => 'password' //Default is 'password' in the userModel
)
)
)
)
);
StudentsController looks like
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->Auth->allow('login');
}
public function login() {
if($this->Session->check('Auth.Student')){
$this->redirect(array('action' => 'login'));
}
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->setFlash(__('Welcome, '. $this->Auth->student('username')));
$this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Invalid username or password'));
}
}
}
And the AppController is
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
}
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'students', 'action' => 'login'),
'loginAction' => array('controller' => 'students', 'action' => 'login'),
));
public function beforeFilter(Event $event) {
$this->Auth->authenticate=array (
'loginAction' => [
'controller' => 'Students',
'action' => 'login',
'plugin' => false,
],
'Basic' => ['userModel' => 'Students'],
'Form' => ['userModel' => 'Students']
);
}
And I have the following error
Component class SessionComponent could not be found.
How can I fix it?
Session was deprecated in cakePHP 3, How you are doing is for cake2. In cake 3 you can use RequestHandeler like,
$this->loadComponent('RequestHandler');
OR
public $components = array(
'RequestHandler'
);
then use,
$this->request->Session()->read/write/delete/destroy();
Hope this will work for you :).
I am trying to call a custom action by ajax, but the response returned is 404, I am pretty sure its a routing issue, but I can't figure how to solve it.
here is my code:
action
public function actionGetOne($id){
$model = Driver::findOne($id);
if(!empty($model)){
$data = [];
$row = [
'id'=>$model->id,
'full_name'=>$model->full_name,
'email'=>$model->email,
'nationality_id'=>$model->nationality_id,
'current_location'=>$model->current_location,
'medical_check_id'=>$model->medical_check_id,
'img'=>$model->img,
'current_fleet_id'=>$model->current_fleet_id,
'availability'=>$model->availability
];
$data[] = $row;
echo json_encode(['driver-getOne'=>'success','data'=>$data]);
} else{
echo json_encode(['driver-getOne'=>'failure']);
}
}
ajax
$.ajax({
url:'<?= urldecode(Url::toRoute(['driver/get-one'])); ?>?id=<?= $id; ?>',
method:'post',
dataType:'json',
success:function(response){}
error:function(){
alert('target action is not found!');
}
}
backend/config/params.php
<?php
return [
'adminEmail' => 'admin#example.com',
'urlRules' => [
'' => 'site/index',
'login/' => 'site/login',
'signup/' => 'site/signup',
'<controller:[\w-]+>/<action:\w+>' => '<controller>/<action>',
'<controller:[\w-]+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:[\w-]+>/<id:\d+>' => '<controller>/view',
'<controller:[\w-]+>/create' => '<controller>/create',
'<controller:[\w-]+>/update/<id:\d+>' => '<controller>/update',
'<controller:[\w-]+>/delete/<id:\d+>' => '<controller>/delete',
'<controller:[\w-]+>/get-all' => '<controller>/get-all',
'<controller:[\w-]+>/get-one' => '<controller>/get-one',
'<controller:[\w-]+>/update-status' => '<controller>/update-status',
]
];
Change few things and try again.
Action:
public function actionGetOne($id)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = Driver::findOne($id);
if (empty($model)) {
return ['driver-getOne' => 'failure'];
}
return [
'driver-getOne' => 'success',
'data' => [[
'id' => $model->id,
'full_name' => $model->full_name,
'email' => $model->email,
'nationality_id' => $model->nationality_id,
'current_location' => $model->current_location,
'medical_check_id' => $model->medical_check_id,
'img' => $model->img,
'current_fleet_id' => $model->current_fleet_id,
'availability' => $model->availability
]],
];
}
Action should return something to properly finish response sequence otherwise unwanted things can happen. By setting response format you can get JSON encoded array automatically.
AJAX:
$.ajax({
url:'<?= Url::to(['driver/get-one', 'id' => $id]) ?>',
method:'post',
dataType:'json',
success:function(response){}
error:function(){
alert('target action is not found!');
}
}
Get your URL using proper syntax.
Params:
'urlRules' => [
'' => 'site/index',
'login' => 'site/login',
'signup' => 'site/signup',
'<controller:[\w-]+>/<id:\d+>' => '<controller>/view',
'<controller:[\w-]+>/<action:[\w-]+>/<id:\d+>' => '<controller>/<action>',
'<controller:[\w-]+>/<action:[\w-]+>' => '<controller>/<action>',
]
I'm assuming you are passing urlRules to components > urlManager > rules otherwise URL rules won't work.
I removed redundant rules. In general add general rules last and specific rules first.
I am getting frusted because the edit.ctp is not recognizing the stored data within a multible value checkbox. This is my code:
Controller:
public function edit($id = null) {
$this->set('userfunc', $this->Auth->user('userfunction_id'));
$user = $this->Users->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
**$selection = explode('#',$user->member);**
$userfunctions = $this->Users->Userfunctions->find('list', ['limit' => 200]);
$userappartments = $this->Users->Userappartments->find('list', ['limit' => 200]);
$userparkings = $this->Users->Userparkings->find('list', ['limit' => 200]);
$this->set(compact('user', 'userfunctions', 'userappartments', 'userparkings', 'selection'));
$this->set('_serialize', ['user']);
}
edit.ctp:
<?php
echo $this->Form->label('User.status', 'Status');
$options = $statusList;
echo $this->Form->radio('status', $statusList);
echo $this->Form->label('User.member', 'Mitglied');
echo $this->Form->input('member', ['options' => $memberList, 'multiple' => 'checkbox', 'label' => false, 'selected' => $selection]);
echo $this->Form->input('userappartment_id', ['options' => $userappartments, 'label' => 'Wohnung']);
echo $this->Form->input('userparking_id', ['options' => $userparkings, 'label' => 'Parkplatz']);
echo $this->Form->input('contact', ['label' => 'Kontakt']);
?>
================
print_r is displaying an array that looks fine:
enter image description here
but the field in the form is emty:
enter image description here
I'm yet to understand what needed to be fixed in the code making it to generate the error. What is to be put right?
This is the code:
public function store(Request $request){
$validator = Validator::make($request->all(), [
'user_id' => 'required|numeric',
'company_id' => 'required|numeric',
'product_id' => 'required|numeric',
'tankerTotankerDesc' => 'alpha_num|min:5',
'tankerTakeOverDesc' => 'alpha_num|min:5',
'costFreightInsuranceDesc' => 'alpha_num|min:5',
'freightOnBoardDesc' => 'alpha_num|min:5',
'tankerTotankerPrice' => 'numeric|required_with:tankerTotankerDesc',
'tankerTakeOverPrice' => 'numeric|required_with:tankerTakeOverDesc',
'costFreightInsurancePrice' => 'numeric|required_with:costFreightInsuranceDesc',
'freightOnBoardPrice' => 'numeric|required_with:freightOnBoardDesc',
'optional_procedure' => 'alpha_num|min:5',
'optional_procedure_price' => 'numeric|required_with:optional_procedure',
'business_type' => 'required'
]);
if ($validator->fails()) {
redirect()->route('productUniqueCreate', $validator)->with('message', 'Record successfully created');
}else{
$product_id = $request->product_id;
$procurementUnique = ProcurementUnique::firstOrNew(array('product_id'=>$product_id));
$procurementUnique->user_id = $user_id;
$procurementUnique->company_id = $request->company_id;
$procurementUnique->product_id = $product_id;
$procurementUnique->productname = $request->productname;
$procurementUnique->ttt_description = $request->tankerTotankerDesc;
$procurementUnique->tto_description = $request->tankerTakeOverDesc;
$procurementUnique->cif_description = $request->costFreightInsuranceDesc;
$procurementUnique->fob_description = $request->freightOnBoardDesc;
$procurementUnique->optional_procedure = $request->optional_procedure;
$procurementUnique->ttt_price = $request->tankerTotankerPrice;
$procurementUnique->tto_price = $request->tankerTakeOverPrice;
$procurementUnique->cif_price = $request->costFreightInsurancePrice;
$procurementUnique->fob_price = $request->freightOnBoardPrice;
$procurementUnique->optional_procedure_price = $request->optional_procedure_price;
$procurementUnique->business_type = $request->business_type;
$procurementUnique->save();
return redirect()->route('productUniqueCreate', $product_id)->with('message', 'Record successfully created');
}
}
Your problem is with this line..
redirect()->route('productUniqueCreate', $validator)->with('message', 'Record successfully created');
Remove the $validator.
redirect()->route('productUniqueCreate')->with('message', 'Record successfully created')->withErrors($validator);