how to check if data already exist when insert data - php

I want to ask how to to check the data if we input data if there is the same data that cannot be inserted.
My code:
$obj = new Pengajuan();
// $obj->id_pengajuan = $req->input('kode');
$obj->id_nasabah = $req->input('id_nasabah');
$obj->tgl_pengajuan = $req->input('tgl_pengajuan');
$obj->besar_pinjaman = $req->input('besar_pinjaman');
$obj->status = $req->input('status');
$simpan = $obj->save();
if ($simpan == 1) {
$status = "Tersmpan";
} else {
$status = "Gagal";
}
echo json_encode(array("status" => $status));

Above of the code add a validation like below:
$this->validate([
'id_nasabah' =>'unique:pengajuans'
]) ;
And then rest of your controller code.

try this:
public function store(Request $request)
{
$this->validate($request,[
'id_nasabah'=>'required|exists:your_table_name,id',
'tgl_pengajuan'=>'more_validations',
'besar_pinjaman'=>'more_validations',
]);
//if $this->validate() fails, it will return a response 422 code error
//else it will continue with the creation of your object
//is a good idea to use a try-catch in case of something goes wrong
try
{
$pengajuan=Pengajuan::create($request->only('id_nasabah','tgl_pengajuan','besar_pinjaman'));
return response->json([
'pengajuan'=>$pengajuan,
'status'=>'Tersmpan',
],200);//return a http code 200 ok
}
catch(Exception $e)
{
//'message'=>'this will return what is the error and line'
return response()->json([
'message'=>$e->getMessage().'/'.$e->getLine(),
'status'=>'Gagal',
],422);
}
}

Related

How to solve Trying to get property of non-object in Laravel

I'm a beginner web developer
I'm trying to write a condition that will be fulfilled depending on what data the user will send
Condition if fulfilled by one hundred percent
But the condition else produces an error with the following text
Trying to get property 'unique_id' of non-object
If someone have info how to solv this problem I will be grateful
This is my code from controller
public function checkRestorePassword(Request $request)
{
$result['success'] = false;
$rules = [
'unique_id' => 'required',
];
$validation = Validator::make($request->all(), $rules);
if (empty($validation))
{
$result['error'] = "Enter the code that was sent to you by mail.";
return response()->json($result, 422);
}
$user = User::where('unique_id', $request->uniqueId)->first();
if ($user->unique_id === $request->uniqueId)
{
$result['success'] = 'Access to your personal account successfully restored. Please change your password.';
return response()->json($result, 200);
}
else
{
$result['success'] = false;
return response()->json($result, 422);
}
}
I think it's because $user is returning null.
so do this
if (!is_null($user) && $user->unique_id === $request->uniqueId)

Laravel CustomRequest authorize, pass request data to validate the auth user customer id and the model id match

I'm trying to fix an if-else statement in the request for my controller. What I'm trying to do is: if the auth::user-companyID == $request-companyID then true else false; The companyID for the request is in a hidden field on the blade file.
CustomRequest
public function authorize()
{
$user = Auth::user();
if ($user->companyID == $request->companyID) {
return true;
} else {
return false;
}
}
Controller
public function edit(EquipmentRequest $request, $id)
{
$validated = $request->validated();
$user = Auth::user();
$equipment = EquipmentModel::where('id', '=', $id)->first();
$equipment->Year = $request->Year;
$equipment->Make = $request->Make;
$equipment->Model = $request->Model;
$equipment->Type = $request->Type;
$equipment->unitNumber = $request->unitNumber;
$equipment->AnnualInspectionDate = $request->AnnualInspectionDate;
$equipment->userID = $request->userID;
$equipment->companyID = $user->companyID;
$e = $equipment->save();
if ($e) {
$request->session()->flash('success', 'The equipment was successfully updated.');
} else {
$request->session()->flash('error',
'An error occurred while saving. Please refresh your browser and try again.');
}
return redirect()->route('equipmentlist');
}
This form worked before I started messing with it so I know the form is working correctly on the blade file. I'm not sure if you can pass the request data the way I'm doing it or if I have to do a construct to do it this way. I would really appreciate any advice.
use Illuminate\Http\Request;
public function authorize()
{
$user = auth()->user();
return $user->companyID === request()->companyID;
}

Laravel- PHP request not setting database values correctly

I have a Laravel application, and on one of the pages, I want to allow the user to be able to update some values in the database, by entering/ changing data in a couple of textboxes.
The Angular function called by the (change) attribute of these HTML textboxes is:
updatePreferredAddresseeDetails($event, payer) {
console.log("updatePreferredAddresseeDetails() called ");
const contact = payer['contacts'][$event.currentTarget.selectedIndex];
payer.loading = true;
payer.originalAddresseeName = payer.addresseename;
payer.originalAddresseeNamePdf = payer.addresseenamepdf;
payer.ADDRESSEENAME = $event.contactPreferredName;
payer.ADDRESSEENAMEPDF = $event.contactPreferredAddresseeName;
this.provService.updatePreferredAddresseeDetails(payer).subscribe(
(response:any) => {
payer.addresseename = response.addresseename;
payer.addresseenamepdf = response.addresseenamepdf;
const message = new Message();
message.type = MessageType.SUCCESS;
message.message = 'Preferred Addressee details have been updated. ';
this.messagingService.emitMessage(message);
payer.loading = false;
},
(error:any) => {
//reset the names back to what they were originally because saving failed
payer.addresseename = payer.originalAddresseeName;
const message = new Message();
message.type = MessageType.ERROR;
message.message = error.message || 'There was a problem updaing the preferred addressee details. If the problem persists, please contact us.';
this.messagingService.emitMessage(message);
payer.loading = false;
}
);
}
The PHP function called by the above Angular function, which should be setting the values in the database is:
public function updatePreferredAddresseeDetails(Request $request)
{
try
{
DB::beginTransaction();
$transactionContactId = $request->input('transactionContactId');
$transactionItemId = $request->input('transactionItemId');
if ($transactionItem = transactionItem::find($transactionItemId))
{
$transaction = $transactionItem->transaction;
if (User::canAccessTransaction( auth()->user()->user, $transaction))
{
$account = Account::find($transaction->accountId);
$account->savePropertyValueByPropertyTag('ADDRESSEENAME', $request->input('contactPreferredName'));
$account->savePropertyValueByPropertyTag('ADDRESSEENAMEPDF', $request->input('contactPreferredAddresseeName'));
$account->save();
DB::commit();
return response()->json([
'success' => true,
'addresseeName' => $account->ADDRESSEENAME,
'addresseeNamePdf' => $account->ADDRESSEENAMEPDF,
]);
}
else
{
return response()->json([
'success' => false,
]);
}
dd("transactionItem: ", $transactionItem);
}
else
{
dd("transactionItem could not be found ");
}
}
catch(Exception $e)
{
$message = $e->getMessage();
if (empty($message))
{
$message = "Preferred addressee details could not be updated. ";
}
DB::rollback();
return response()->json([
'error' => true,
'message' => $message
], 500);
}
}
However, when I enter new values/ update an existing value in one of the textboxes, and then tab out of it, I can see in the browser console that the Angular function is called, and that it in turn calls the PHP function- but in the Network->Preview tab of the console, I see the output:
{success: true, addresseeName: null, addresseeNamePdf: null}
addresseeName: null
addresseeNamePdf: null
success: true
so for some reason, it seems that these values are not actually being updated in the database. Why is this? What am I doing wrong? How can I ensure that the database values are correctly updated from this function?
Edit
Looks like #Devon was possibly right with his comment about the function being used... I had a look the user.php file (which is where canAccessTransaction() is defined), and there was another function: userCanEditAccount(), which I think is probably the one I want. It's defined with:
private static function userCanEditAccount($userId, $accountId)
{
return Account::canUserEditAccount( $userId, $accountId );
}
so I changed that part inside the updatePreferredAddresseeDetails() function to:
if(User::userCanEditAccount( $request->userId, $request->accountId)
{
$account = Account::find($request->accountId);
$account->savePropertyValueByPropertyTag('ADDRESSEENAME', $request->input('contactPreferredName'));
$account->savePropertyValueByPropertyTag('ADDRESSEENAMEPDF', $request->input('contactPreferredAddresseeName'));
$account->save();
dd("request: ", $request->all());
DB::commit();
return response()->json([
'success' => true,
'addresseeName' => $account->ADDRESSEENAME,
'addresseeNamePdf' => $account->ADDRESSEENAMEPDF,
]);
}
else
{
return response()->json([
'success' => false,
]);
}
But when the page loads now, before I actually interact with it at all, I get an error in the console that says:
Parse error: syntax error, unexpected ';'
on the line
$account = Account::find($request->accountId);
but I'm pretty sure that ; should be there- what else could be causing this?

How to print out text in beforeAction in Yii2

How to print out data within function beforeAction? I want to make some verification before each action in a controller, therefore if some condition occurs in beforeAction I should print out data and prevent further execution, for example, JSON:
[
status: "error",
msg: "access denied"
]
I try to even inner redirect to another controller, but it doesn't work.
public function beforeAction($action)
{
$request = Yii::$app->request;
if ( ! checkByToken($request->get('token')) && $this->getRoute() != 'web/abonent/token_error') {
\Yii::$app->runAction('web/abonent/token_error');
return true;
}
return parent::beforeAction($action); // TODO: Change the autogenerated stub
}
But maybe there an another concept of doing so. I just need to check the condition before any actions and print our result or let the action execute.
To prevent further execution:
public function beforeAction($action) {
return false; // key point
}
To print out data within beforeAction:
public function beforeAction($action) {
// set response format = json:
Yii::$app->response->format = Response::FORMAT_JSON;
// then, set the response data:
Yii::$app->response->data = [
'status' => 'error',
'msg' => 'access denied'
];
return false;
}
I think will be better
public function beforeAction($action)
{
$request = Yii::$app->request;
if ( ! checkByToken($request->get('token')) && $this->getRoute() != 'web/abonent/token_error') {
$action = 'error';
}
return parent::beforeAction($action); // TODO: Change the autogenerated stub
}
Action name must be 'actionError'

Yii2; code running in "else" block first, and then running code before "if" block?

I'm completely lost as to why this is happening, and it happens about 50% of the time.
I have a check to see if a user exists by email and last name, and if they do, run some code. If the user doesn't exist, then create the user, and then run some code.
I've done various testing with dummy data, and even if a user doesn't exist, it first creates them, but then runs the code in the "if" block.
Here's what I have.
if (User::existsByEmailAndLastName($params->email, $params->lastName)) {
var_dump('user already exists');
} else {
User::createNew($params);
var_dump("Creating a new user...");
}
And here are the respective methods:
public static function existsByEmailAndLastName($email, $lastName) {
return User::find()->where([
'email' => $email,
])->andWhere([
'last_name' => $lastName
])->one();
}
public static function createNew($params) {
$user = new User;
$user->first_name = $params->firstName;
$user->last_name = $params->lastName;
$user->email = $params->email;
$user->address = $params->address;
$user->address_2 = $params->address_2;
$user->city = $params->city;
$user->province = $params->province;
$user->country = $params->country;
$user->phone = $params->phone;
$user->postal_code = $params->postal_code;
return $user->insert();
}
I've tried flushing the cache. I've tried it with raw SQL queries using Yii::$app->db->createCommand(), but nothing seems to be working. I'm totally stumped.
Does anyone know why it would first create the user, and then do the check in the if statement?
Editing with controller code:
public function actionComplete()
{
if (Yii::$app->basket->isEmpty()) {
return $this->redirect('basket', 302);
}
$guest = Yii::$app->request->get('guest');
$params = new CompletePaymentForm;
$post = Yii::$app->request->post();
if ($this->userInfo || $guest) {
if ($params->load($post) && $params->validate()) {
if (!User::isEmailValid($params->email)) {
throw new UserException('Please provide a valid email.');
}
if (!User::existsByEmailAndLastName($params->email, $params->lastName)) {
User::createNew($params);
echo "creating new user";
} else {
echo "user already exists";
}
}
return $this->render('complete', [
'model' => $completeDonationForm
]);
}
return $this->render('complete-login-or-guest');
}
Here's the answer after multiple tries:
Passing an 'ajaxParam' parameters with the ActiveForm widget to define the name of the GET parameter that will be sent if the request is an ajax request. I named my parameter "ajax".
Here's what the beginning of the ActiveForm looks like:
$form = ActiveForm::begin([
'id' => 'complete-form',
'ajaxParam' => 'ajax'
])
And then I added this check in my controller:
if (Yii::$app->request->get('ajax') || Yii::$app->request->isAjax) {
return false;
}
It was an ajax issue, so thanks a bunch to Yupik for pointing me towards it (accepting his answer since it lead me here).
You can put validation like below in your model:
public function rules() { return [ [['email'], 'functionName'], [['lastname'], 'functionforlastName'], ];}
public function functionName($attribute, $params) {
$usercheck=User::find()->where(['email' => $email])->one();
if($usercheck)
{
$this->addError($attribute, 'Email already exists!');
}
}
and create/apply same function for lastname.
put in form fields email and lastname => ['enableAjaxValidation' => true]
In Create function in controller
use yii\web\Response;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else if ($model->load(Yii::$app->request->post()))
{
//place your code here
}
Add 'enableAjaxValidation' => false to your ActiveForm params in view. It happens because yii sends request to your action to validate this model, but it's not handled before your if statement.

Categories