Checking existing record based on two fields - mysql

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

Related

API Create Multiple Input Laravel

I'm currently creating API for multiple inputs using laravel. The data will be stored into two tables : Order and Detail_Order. One order can have many detail orders.
But now, the data only stored into Order table, and got an error: ErrorException: Invalid argument supplied for foreach() in file. Does anyone know how? Thank you.
Here's my code :
public function createDetail($total_passenger, $id_trip, $id_users, Request $request){
$trip = Trip::where(['id_trip' => $id_trip])->get();
$seat = $request->id_seat;
if(Detail_Order::where(['id_trip' => $id_trip, 'id_seat' => $seat])
->where('status', '!=', 5)
->exists()) {
return $this->error("Seat has been booked");
}else{
$order = new Order();
$order_select = Order::select('id_order');
$order_count = $order_select->count();
if ($order_count === 0) {
$order->id_order = 'P1';
}else{
$lastrow=$order_select->orderBy('created_at','desc')->first();
$lastrow_id = explode('P', $lastrow->id_order);
$new_id = $lastrow_id[1]+1;
$order->id_order = 'P'.$new_id;
}
$order->id_trip = $id_trip;
$order->id_users = $id_users;
$order->date_order = date('Y-m-d H:i:s');
$order->id_users_operator = 'O4';
$order->save();
foreach($request->passenger_name as $key => $value){
Detail_Order::create([
'id_trip' => $order->id_trip,
'id_seat' => $request->id_seat[$key],
'id_order' => $order->id_order,
'passenger_name' => $request->passenger_name[$key],
'gender' => $request->gender[$key],
'departure' => $request->departure[$key],
'destination' => $request->destination[$key],
'phone' => $request->phone[$key],
'status' => 1
]);
}
return response()->json([
'status' => true,
'message' => "Successfully saved data",
'data' => $order
]);
}

is it possible to create an email only authentication from existing email-password structure in Laravel

I am trying to create email only authentication. Instead of having a login, I want a situation where I will only have signup and once the email is entered, a bearer token is created.
I have the signup function and login function which worked when I had password initiated but I have removed the password but I tried to move the "create token" to signup. It gives error that token is undefined.
Signup function
public function signup(Request $request)
{
$request->validate([
'email' => 'required|string|email|unique:users'
]);
$user = new User([
'email' => $request->email
]);
$user->save();
return response()->json([
'message' => 'Successfully created user!'
], 201);
}
Login function
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email'
]);
$credentials = request(['email', '=']);
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();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
]);
}
It is really simple, you have already done most of the work needed to be done here. You don't need the login function rather you need to copy the token part of the function as illustrated below
public function signup(Request $request)
{
$request->validate([
'email' => 'required|string|email|unique:users'
]);
$user = new User([
'email' => $request->email
]);
$user->save();
Auth::login($user);
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'message' => 'Successfully created user!',
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
], 201);
}

Undefined index: password with JWTAuth

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

Object of class Illuminate\Validation\Validator could not be converted to string

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

Drupal 7 form insert if already exists show message like already existed filed

function countries_form($form, &$form_state,$id=0) {
if($id!=0){
$result = db_query('SELECT * FROM {countries} WHERE id = '.$id.'')->fetch();
// print_r($result);exit;
$form['country_name'] = array(
'#type' => 'textfield', //you can find a list of available types in the form api
'#title' => 'Country name',
'#size' => 30,
'#maxlength' => 30,
'#default_value' => $result->country_name,
'#required' => TRUE, //make this field required
);
$form['description'] = array(
'#type' => 'textarea', //you can find a list of available types in the form api
'#title' => 'Description',
'#default_value' => $result->description,
'#required' => TRUE, //make this field required
);
$form['status'] = array(
'#type' => 'radios',
'#title' => t('Status'),
'#default_value' => $result->status,
'#options' => array(
'1' => t('Active'),
'0' => t('Inactive'),
),
);
}else{
$form['country_name'] = array(
'#type' => 'textfield', //you can find a list of available types in the form api
'#title' => 'Country name',
'#size' => 30,
'#maxlength' => 30,
'#required' => TRUE, //make this field required
);
$form['description'] = array(
'#type' => 'textarea', //you can find a list of available types in the form api
'#title' => 'Description',
'#required' => TRUE, //make this field required
);
}
$form['submit_button'] = array(
'#type' => 'submit',
'#value' => t('Click Here!'),
);
return $form;
}
function countries_form_submit($form, &$form_state) {
//$result = db_query('SELECT country_name FROM {countries}')->fetch();
//print_r($result);
if(arg(2)!=0){
$query = db_update('countries')->fields(array('country_name'=>$form_state['values']['country_name'],'description'=>$form_state['values']['description'],'status'=>$form_state['values']['status']))->condition('id',arg(2));
$query->execute();
// print_r($query);
drupal_set_message(t('Country %name has been updated.', array('%name' => $form_state['values']['country_name'])));
//print_r($description);
}else{
//$query = db_update('countries')->fields(array('country_name'=>$form_state['values']['country_name'],'description'=>$form_state['values']['description'],'status'=>$form_state['values']['status']))->condition('country_name','%s');
// print_r($query);
$query = db_insert('countries')->fields(array('country_name'=>$form_state['values']['country_name'],'description'=>$form_state['values']['description']));
//print_r($query);
$query->execute();
drupal_set_message(t('Country %name has been saved.', array('%name' => $form_state['values']['country_name'])));
}
//exit;
$form_state['redirect'] = 'mypages/table';
}
bu using druapl 7 form I am inserting and displaying date and editing and deleting as well all working fine..
now i want ..when inserting form we need to show message if already filed exists country name already taken like that..
there is not update query required only query for while inserting value check weather it is existed or not...
in that the below code is used or edit by passing arguments..
if(arg(2)!=0){
$query = db_update('countries')->fields(array('country_name'=>$form_state['values']['country_name'],'description'=>$form_state['values']['description'],'status'=>$form_state['values']['status']))->condition('id',arg(2));
$query->execute();
// print_r($query);
drupal_set_message(t('Country %name has been updated.', array('%name' => $form_state['values']['country_name'])));
//print_r($description);
}else{
in the else code inserting here we need to check weather existed or not