Eloquent update all column fields - php

I want to update all the tables in the Article migration to a specific Boolean value which is set by the user.
I have written this code:
public function changeComVote() {
$data = request()->validate([
'status' => 'required'
]);
Article::query()->update(['isOnly' => $data['status']]);
event(new changesMade);
}
Although $data['status'] doesn't get passed inside the query and nothing happens, when i set it manually it works like a charm, what could be the problem?

Using $data['status'] from request will give you a string as a result, not a boolean.
Try this way
Article::query()->update(['isOnly' => $data['status'] == 'true']);

You can delete that "query()" thing and use this instead
Article::update(['isOnly' => $data['status']]);
or
Article::update(['isOnly' => ($data['status']] === "true"));
You can also specify where the row by using id
Article::find($id)->update(['isOnly' => ($data['status']] === "true"));

Related

How to get the inserted id of create() method in laravel?

I'm trying to get the last inserted id made from create() eloquent in laravel.
Here's my laravel code
$product = ProductModel::create([
'prodCode' => $prodCode,
'prodTitle' => $dataProducts->prodTitle,
'prodDesc' => $dataProducts->prodDesc,
'attachment' => "images/products/".$attachment,
'prodSize' => $dataProducts->prodSize,
'prodCategory' => $dataProducts->prodCategory,
'prodPrice' => $dataProducts->prodPrice,
'created_by' => auth()->user()->id
]);
I will use this last inserted id for another query with the same function.
Is it possible to do it with this way of saving data, or do I need to convert this code to another efficient way?
The create function of a model returns new record.
Very easily:
$product = ProductModel::create([...]);
// last inserted id
$lastInsertedId = $product->$idField;
Well in this case your are doing right !
use print_r($product->id) to see the last inserted id if the field name is id

Not getting the id in where clause - Laravel 5.2

I need to get the record with special id and i have this in my method :
public function addedMark()
{
$user = Auth::user();
$subject = ClassSubject::where('teacher_id', $user->id)->pluck('id','subject_id');
return view('educator.account.marks', [
'user' => $user,
'marks' => StudentMark::where('subject_id', $subject)->get()
]);
}
When i do dd(ClassSubject::where('teacher_id', $user->id)->pluck('id','subject_id')); i see that I'm getting the information that i need, but when i do dd(StudentMark::where('subject_id', $subject)->get()); it returns an empty array.
Any idea why?
Change it to (whereIn)
'marks' => StudentMark::whereIn('subject_id', $subject)->get()
and let see what hapens
In $subjectyou have id and subject_id. You might wanna just take subject_id.
So change this: StudentMark::where('subject_id', $subject)->get()
to
StudentMark::where('subject_id', $subject[1])->get()

PHP If statement returns false on MySQL boolean column return

I am using the CodeIgniter framework. I'm working on the user authentication portion of my website. In my 'users' table of my MySQL database I have a column that I declared as a BOOLEAN (I am aware that it really is a TINYINT(1)) called 'verified' that denotes whether or not a user's email address has been verified. When I try to test the value of this column, my IF statement always evaluates to FALSE, even though I know for a fact the value is 1. Here is a snippet of my code:
public function authenticate_user(){
$pw = hash('sha512', $this->salt1 . $this->input->post('password') . $this->salt2);
$email = $this->input->post('email');
$query = $this->db->get_where('users', ['email' => $email, 'password' => $pw]);
if($query->num_rows() == 1){
$row = $query->row_array();
//die("verified = ".$row['verified']); <-This line shows 'verified = 1' consistently when uncommented.
if($row['verified'] == 1){
$this->session->set_userdata([
'name' => $row['name'],
'email' => $email,
'login_time' => time(),
'last_activity' => time(),
'session_valid' => TRUE
]);
return true;
}
else return 'unverified';
}
else return false;
}
When the credentials are correct, this function always returns 'unverified' and no session variables are set. The function exhibits the correct behavior when the credentials are incorrect. I have confirmed in phpMyAdmin that the column is 1, and I have confirmed that 1 is returned from the database by uncommenting the die() statement above. I have tried using true and '1' (string) in place of the integer 1 and have gotten the same result. Am I doing something wrong? Does CodeIgniter preprocess database returns in a way that would make this not work?
#Sean, your suggestion works. I'm not sure why PHP evaluates it differently than when using the == operator. The way it works is:
if($row['verified'])
Thank you for you help guys.
Try using the empty() function in the if clause:
if(!empty($row['verified'])){
$this->session->set_userdata([
'name' => $row['name'],
'email' => $email,
'login_time' => time(),
'last_activity' => time(),
'session_valid' => TRUE
]);
return true;
}

Update only one field on Cakephp 3

In some part of my app I need to update only the field is_active of some table with a lot of fields. What is the best approach to update only this field and avoid the validations and requiriments of all other fields?
And if you want to update particular row only , use this:
$users= TableRegistry::get('Users');
$user = $users->get($id); // Return article with id = $id (primary_key of row which need to get updated)
$user->is_active = true;
// $user->email= abc#gmail.com; // other fields if necessary
if($users->save($user)){
// saved
} else {
// something went wrong
}
See here (Updating data in CakePHP3).
This will work:
$users = TableRegistry::get('Users');
$query = $users->query();
$query->update()
->set(['is_active' => true])
->where(['id' => $id])
->execute();
http://book.cakephp.org/3.0/en/orm/query-builder.html#updating-data
When you don't want callbacks to be triggered, just use updateAll()
$table->updateAll(['field' => $newValue], ['id' => $entityId]);
Using the example here: http://book.cakephp.org/3.0/en/orm/database-basics.html#running-update-statements. Run the code below to update all records in table_name_here table with a new value for is_active column.
use Cake\Datasource\ConnectionManager;
$connection = ConnectionManager::get('default');
$connection->update('table_name_here', ['is_active' => 'new_value_here']);
I faced this issue when upgrading my project from 2.10 to 3.x.
In 2.10 you could update a single field using:
$this->Menus->saveField('css', $menucss);
But since this method was deprecated, we do as below now, considering that callbacks will not be triggered:
$this->Menus->updateAll(['css' => $menucss], ['id' => $menu_id]);
The other answers don't use internationalization and other models props, callbacks, etc.
I think this is because of the query builder, it does not use the models and so their behaviors, therefore you should use:
$this->loadModel('Inputs');
$input = $this->Inputs->find()->where(['`key`' => $this->request->data['id']])->first();
$this->Inputs->patchEntity($input, ['prop' => $this->request->data['prop']]);
if ($this->Inputs->save($input)) {
die(json_encode(true));
} else {
die(json_encode(false));
}

Set field value for single database row

I'm trying to update a row on my profiles table to reset a users profile picture to the default of user.png. I have the following action in my controller:
public function deleteProfilePicture() {
$this->layout = 'ajax';
// First find the profile ID from the user ID
$profileId = $this->Profile->find('first', array(
'condition' => array('User.id' => $this->Auth->user('id')),
'fields' => array('Profile.id'),
'recursive' => -1
));
$this->Profile->id = $profileId['Profile']['id'];
$this->Profile->saveField('picture', 'user.png', false);
}
However, when I request the URL (/profile/deleteProfilePicture) I get no errors but the database row isn't updated. I have made sure the current profile ID is used by using debug($profileId).
What could be going wrong here?
Edit: The return value of saveField():
array(
'Profile' => array(
'id' => '36',
'modified' => '2013-04-05 14:16:57'
)
)
Try
$this->Profile->id = $profileId['Profile']['id'];
$this->Profile->set(array(
'picture' => 'user.png'
));
$this->Post->save();
I see no error in your code. Try seeing what query is getting executed using this
$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);
based on the result make changes to your query if you find something wrong.
Or try using this
$data['Profile']['id']=$profileId['Profile']['id'];
$data['Profile'['picture']='user.png';
$this->Profile->save($data);
If you set debug to 2 you could see what SQL is being executed, see if your update is actually firing.
Try this
$this->Profile->read(null, $profileId['Profile']['id']);
$this->Profile->saveField('picture', 'user.png', false);
Why are you setting the validation to false? Do you get an error if you omit that?

Categories