Error with "ID" in crud with CodeIgniter 3 when updating a record in SQLSERVER database [closed] - codeigniter

Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 5 days ago.
Improve this question
My problem arises when I want to update a database record, the same code works for me when I implement a MySql database, when I change to SQLSERVER it generates the following error
**
**Error Number: 42000/8102
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot update identity column 'id'.****
CONTROLADOR
`public function update()
{
if ($this->input->is_ajax_request()) {
$this->form_validation->set_rules('edit_name', 'Name', 'required');
$this->form_validation->set_rules('edit_email', 'Email', 'required|valid_email');
if ($this->form_validation->run() == FALSE) {
$data = array('responce' => 'error', 'message' => validation_errors());
} else {
$data['id'] = $this->input->post('edit_record_id');
$data['name'] = $this->input->post('edit_name');
$data['email'] = $this->input->post('edit_email');
if ($this->crud_model->update_entry($data)) {
$data = array('responce' => 'success', 'message' => 'Record update Successfully');
} else {
$data = array('responce' => 'error', 'message' => 'Failed to update record');
}
}
echo json_encode($data);
} else {
echo "No direct script access allowed";
}
}`
MODELO
** public function update_entry($data)
{
return $this->db->update('crud', $data, array('id' => $data['id']));
}**

Related

How to create endpoint to post data and the response is nested array in Laravel 8

I'm a beginner in Laravel and I would like to make API with the response like this
elements: [
{
title:
"Please indicate if you agree or disagree with the following statements",
question: [
{
value: "affordable",
text: "Product is affordable",
},
{
value: "does what it claims",
text: "Product does what it claims",
},
{
value: "better then others",
text: "Product is better than other products on the market",
},
{
value: "easy to use",
text: "Product is easy to use",
},
],
},
],
here's code in my migration database :
Schema::create('question_surveys', function (Blueprint $table) {
$table->id('question_survey_id');
$table->string('title');
$table->json('question');
$table->timestamps();
});
and in my controller, for store the data that I have created, I tried this
$validation = $request->validation([
'title' => 'required|string',
'question' => 'required|json',
]);
try {
$response = QuestionSurvey::create($validation);
return response()->json([
'success' => true,
'message' => 'Survey Question Successfully Created',
'data' => $response,
'code' => 200
], 200);
} catch (\Exception $e) {
return response()->json([
'message' => 'Something wrong, content was not created successfully',
'errors' => $e->getMessage()
]);
}
I tried to post data in postman, the code return 200 but not successfully created. I'm confused what should I do and what the exactly keyword I should search on google to solve this problem. I'm very thankful if you can help me to solve this problem..
instead of these code you can create a table questions and relate it with question_surveys, One To Many Relationships, like:
first create table questions and set value and text as columns, then just add a foreign key to question_surveys tabel like: $table->foreignId('question_survey_id'); in the migration.
now you have to ways. 1- create spread CRUD for questions or in store question_surveys send all questions in an array, after store question_surveys store questions with foreign key, question_survey_id.
in the question_surveys model write:
public function question()
{
return $this->hasMany(Question::class);
}
and in Question model write:
public function question_surveys()
{
return $this->belongsTo(QuestionSurvey::class);
}
now when you find QuestionSurvey:
$question_survey = QuestionSurvey:://your query;
$question_survey->question; // get all questions related to this `question_surveys`
not: if $question_survey is array, put $question_survey->question in resource.

Expected response code "250/251/252" but got code "451", with message "451 Temporary local problem - please try later"

I am new in Laravel development. I am sending an email to agencies which is approved and email is not null and if agencies email is null then get customer email for send email, But I got this error https://flareapp.io/share/DPygyxQ5#F57
I have tried to figure out where is the issue using echo pre in every steps. I am using smtp for sending email.
If you think that is there issue in smtp so if user register itself then email is successfully sent to user.
Here is code
// Get agency details
$agencies = Agency::where('status', 2)->get();
$property = Property::where('property_id', $id)->first();
if($agencies->isNotEmpty())
{
foreach($agencies as $agency)
{
if($agency->email != null)
{
$agency_name = $agency->name;
$agency_email = $agency->email;
$property_slug = $property->slug;
$property_link = route('property.detail', $property_slug);
Mail::send('emails.user.agency.mail_to_agency_after_property_approve',
[
'agency_email' => $agency_email,
'agency_name' => $agency_name,
'property' => $property,
'property_link' => $property_link,
],
function($message) use ($agency_email)
{
$message->to($agency_email);
$message->subject('Fresh Property Listing Update');
});
}
else
{
$customer = Customer::select('customer_id', 'first_name', 'last_name', 'customer_email')->where('customer_id', $agency->customer_id)->first();
$agency_name = $customer->first_name.' '.$customer->last_name;
$agency_email = $customer->customer_email;
$property_slug = $property->slug;
$property_link = route('property.detail', $property_slug);
Mail::send('emails.user.agency.mail_to_agency_after_property_approve',
[
'agency_email' => $agency_email,
'agency_name' => $agency_name,
'property' => $property,
'property_link' => $property_link,
],
function($message) use ($agency_email)
{
$message->to($agency_email);
$message->subject('Fresh Property Listing Update');
});
}
}
}

how to perform bulk update with change check in laravel?

I am using laravel, I am using this code in the update function. works fine, but is it possible to save lines of code with bulk insertion?
Example: $product->update($request->all());
But first check if they have sent new data to update.
My Function Update:
public function update(ProductUpdateRequest $request, Product $product)
{
$data = Product::findOrFail($product->id);
$data->category_id = $request->category_id;
$data->name_product = $request->name_product;
$data->description = $request->description;
$data->stock = $request->stock;
$data->price_buy = $request->price_buy;
$data->price_sale = $request->price_sale;
$data->status = $request->status;
if ($data->isDirty()) {
$data->update($request->all());
return response()->json([
'color' => 'green',
'message' => 'CATEGORY EDIT'
]);
} else {
return response()->json([
'color' => 'red',
'message' => 'NO CHANGE DETECTED'
]);
}
}
You can use fill() method to fill the model with data without committing to database. Do the dirty check and then save. Eg:
public function update(ProductUpdateRequest $request, Product $product)
{
$product->fill($request->all()); //no need to use product->find since $product with the id is already injected
if ($product->isDirty()) {
$product->update($request->all()); //or use $product->save(); since model is alraedy filled with new data
return response()->json([
'color' => 'green',
'message' => 'CATEGORY EDIT'
]);
} else {
return response()->json([
'color' => 'red',
'message' => 'NO CHANGE DETECTED'
]);
}
}
Do note that save method actually checks if the model is dirty. So, if you do not want to send custom messages based on whether the model was changed or not, you could just call save() instead of update() without the dirty check.

Laravel auth attempt not working or returning false always?

I've been looking all over the place (I checked all the other duplicate questions and answers ), no luck. I don't understand what am I doing wrong, all the values are coming from post, but Auth:attempt keeps on failing/returning false, if I try to implement login manually it won't authenticate as I am expecting, Also do I have to make or use separate methods like for validation, credentials, username ..etc ?
Here is my login Controller > login method
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'usermail' => 'required|max:255',
'password' => 'required_with:usermail',
],[
'password.required_with' => "The password field is empty."
]);
if ($validator->fails()) {
return redirect()
->route('admin.login')
->withErrors($validator)
->withInput();
}
$usermail = $request->get('usermail');
$password = $request->get('password');
$remember = $request->get('rememberMe');
if(filter_var($usermail, FILTER_VALIDATE_EMAIL)) {
$isEmailExist = User::where('user_email',$usermail)->first();
if($isEmailExist != null){
if(Auth::attempt([
'user_email' => $usermail,
'user_pass' => $password
])){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the email address <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid email address.'
]);
}
}else{
$isUsernameExist = User::where('user_login',$usermail)->first();
if($isUsernameExist != null){
if(Auth::attempt([
'user_login' => $usermail,
'user_pass' => $password
],$remember)){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the username <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid username. Lost your password?'
]);
}
}
}
And this is my user migration schema,
Schema::create('vw_users', function (Blueprint $table) {
$table->bigIncrements('ID');
$table->string('user_login','60')->unique()->default('');
$table->string('user_pass');
$table->string('user_email','100')->unique()->default('');
$table->rememberToken();
});
Here is how i seed user,
User::create([
'user_login' => 'admin',
'user_pass' => Hash::make("123456"),
'user_email' => 'admin#gmail.com',
]);
OK OK OK,
I made it work, I think in laravel framework we can only create the column name for the password is "password" field in database authentication table.
I updated the following changes:-
I renamed the password field name from migration schema the "user_pass" to "password". (Also updated in login controller and user model).
Added following code into user model:-
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
...
}
I checked twice to confirm so I revert back it didn't work.
If i make any sense to anyone please let me know and help me understand.
I've looked into very similar posts like this Laravel: How can i change the default Auth Password field name
can I please have a reference book or blog for all the laravel predefined libraries and functions? I know the vendor folder is full of surprises but still, I need more references.
Thank you so much for your time.

How to exclude a perticular field from unique validation in edit mode in cakephp3.0 validation

I want to validate a field called survey_id which is an input from user for uniqueness. It is working properly and giving the correct response when adding the new record, but when I tried to edit this record it is giving an error [unique] => Provided value already exist. So what I want is to exclude the survey_id of the current record from uniqueness check and if user input some other value for survey_id it should check for uniqueness search.
Currently I am using the CakePHP 3.0 validation with on create validation. Here is the validation rule that I am using:
validator
->requirePresence('survey_id', __('msg_required'))
->notEmpty('survey_id', __('msg_required'))
->maxlength('survey_id', 32, __('msg_maxlength'))
->add('survey_id', 'unique', ['rule' => ['validateUnique',['id']], 'provider' => 'table', 'message' => 'Provided value already exist', 'on'=>'create']);
return $validator;
Is there anything wrong with this code?
Thanks in advance.
`
It will work with this validation rule
$validator
->requirePresence('survey_id', __('msg_required'))
->notEmpty('survey_id', __('msg_required'))
->maxlength('survey_id', 32, __('msg_maxlength'))
->alphaNumeric('survey_id', __('msg_surveyid_format'))
->add('survey_id', 'custom', [
'rule' => function ($value, $context) {
if (!empty($context['data']['projectId'])) { $values = array($context['data']['projectId']); } else { $values = array(); }
$data = $this->getSurveyId($value, $values);
return (!empty($data)) ? false : true;
},
'message' => __('msg_surveyid_exsist')]);
return $validator;
}
public function getSurveyId($surveyId = null, $exclude = null) {
$where = array('p.survey_id' => $surveyId);
if (!empty($exclude) && is_array($exclude)) {
$where[] = array('p.id NOT IN' => $exclude);
}
return $this->db->newQuery()
->select('*')
->from(['p' => 'projects'])
->where($where)
->execute()
->fetch('assoc');
}

Resources