Data is not updating in mysql through laravel - mysql

I have made a table of users and during the time of registration, i am inserting the necessary data like email password and name and marked others columns null. Everything was working fine until i tried to update the null columns as per requirement. I have tried many methods to update the data but it always says 200 OK in postman but not update the Mysql table.Here is my code
$data = $request->validate([
'dob' => 'required',
'gender'=>'required|in:male,female',
'image'=>'required|mimes:jpg,png,jped|max:5048'
]);
$newImage = time().'-'.$request->name.'.'.$request->image->extension();
$request->image->move(public_path('images'), $newImage);
$user = User::find($id);
$user->update($request->all());
return response($user);
And this my output the name id and email field were added on the time of registeration what i am trying to add is 'dob','gender' and ''profile picture
After trying the method provided i got this

The answer to this question was don't use 'PUT' request to update the data. Some times it works well and some times it will not work. Just use post method just like to create data. It solved my problem.

$user = User::find($id);
$user ->dob = $request->dob;
$user ->gender = $request->gender;
$user ->image= $newImage;
$user ->save();
try this will 100% update your users details .
I hope you got your solution .

Related

cakephp 3 save data to database dont work after adding new column

Hey i want to save data to my database with cakephp 3.8. All works but i added a new field "created_by" and changed it in the models folder.
this is my RequestTable.php
public function validationDefault(Validator $validator){
.... (more, but not important)
$validator
->scalar('created_by')
->maxLength('created_by', 100)
->allowEmptyString('created_by');
return $validator;
}
My entity file "Request.php"
in the top
* #property string|null $created_by
and
protected $_accessible = [
... (more)
'created_by' => true,
];
My code where i want to save the data:
$request = $this->Requests->newEntity();
$session = $this->getRequest()->getSession();
if(!empty($session->read('Auth.User.username'))){
$this->request->data['Requests']['created_by'] = $session->read('Auth.User.username');
}
$request = $this->Requests->patchEntity($request, $this->request->getData('Requests'));
if ($result = $this->Requests->save($request)) {
...
}
At the empty check it goes in the clause. After the patchEntity the result is the correct data. The same in the save.
The column in the table looks like
created_by varchar(100) DEFAULT NULL
I dont know why it doesnt save the data. If someone have more questions about the code please ask :)
Without an error message. It would be hard to determine where is the flaw. One thing you might consider is checking the database if it is busy handling another process. If there are flood requests that makes your request locked.
I dont know why, but if I create a new database with the same schema it works. Thank you all for your help :)

Trying to update a column in database but NOT NULL attributes are not letting me update the values. I am using Laravel

I am trying to update the column with some other data but database table is not letting me update the table because of the NOT NULL constraints in it. I have this option of setting all the fields to NULL but I dont think that will be a good practice. Please I need a solution to it if anyone can help. I get the following error
Illuminate \ Database \ QueryException (HY000)
SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (SQL: insert into users (subject_id, updated_at, created_at) values (?, 2019-07-30 13:46:42, 2019-07-30 13:46:42))
Previous exceptions
SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (HY000)`
I have tried setting all the values to NULL and it worked but I want to work with some fields setting as NOT NULL and update the ones which are NULL and also if we can fetch or set the fields automatically to what we have ?
This is my controller where I am trying to update the field if this is required or help you understand my problem
public function deleteSubject($id) {
echo $id;
// die();
if(Auth::check()) {
$findSubject = Auth::user()->where('subject_id', $id);
$users = new User();
$users->subject_id = null;
$users->save();
// echo($findSubject);
// die();
Session::flash("message", "You subject has been deleted. You can add a new Subject now.");
return redirect('/subjects');
} else {
Session::flash("message", "Please sign in to access this page");
return redirect('/signup');
}
}
The following should work for your code. As it was said in the previous comment, it's because you try to create a new instance of a user without inserting value.
It look like you are trying to delete the subject associate with the authenticated user, so I suppose that you don't really need to create a new user, instead I think you should dissociate the user and the subject. So, the following should work for your code.
The purpose of that variant is to take the authenticated user and put a null value for the subject_id.
public function deleteSubject($id) {
echo $id;
// die();
if(Auth::check()) {
$user = User::where('subject_id', $id)->first(); // This will get the user that have the subect_id, but it's assuming that only one user have this subject_id.
// You can also do this just uncomment the first line below and comment the other one above.
// $user = User::find(Auth::user->id);
$user->subject_id = null;
$user->save()
Session::flash("message", "You subject has been deleted. You can add a new Subject now.");
return redirect('/subjects');
} else {
Session::flash("message", "Please sign in to access this page");
return redirect('/signup');
}
}
I think that you should take a look about how MVC work.
https://selftaughtcoders.com/from-idea-to-launch/lesson-17/laravel-5-mvc-application-in-10-minutes/
You should also take a look at relationship in Laravel: https://laravel.com/docs/5.8/eloquent-relationships
MVC and Eloquent-Relationships will help you understand some function in laravel to achieve this kind of goal really quickly.
If you get a User model and a Subject model, you can simply do something like this:
$user = User->find(Auth::user()->id);
$user->subjects()->dissociate($id);
I'm not sure, but I think the Auth facade let you use the user model function, so maybe this could work to:
Auth::user()->subjects()->dissociate($id);
You should also take a look at middleware: https://laravel.com/docs/5.8/middleware
With middleware, you can put rules like the one you are using to send a message to the user saying that he/she need to be log in to access the page into the middleware and reusing it whenever you need.

laravel where clause return null even if data exists

I tried to query for data in user controller but return only null even when data exist.
$user = DB::table('users')->where('email','=','dumitriucristian#yahoo.com')->first();
if I do:
$user = DB::table('users')->get();
it returns all the data so the db is ok. What it wrong?
That value is not present or you must have a typo in your database. Please check it.

What is wrong with this Code Igniter mySQL query?

I have two tables for storing information about a user. One is for authentication, the other is information the user will enter themselves. I am writing a model that will be used when the user interacts with this information. The following method is to return data for display and modification.
I need a query that will return 'email' and 'username' from $accounts_table and * from $profiles_table. I can't seem to get my head around the JOIN syntax though. I understand how joins work, but my queries throw sentax errors.
function get_userdata($id){
$data = array();
$this->db->get_where($this->profiles_table, array('user_id' => $id));
$this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
$data= $this->db->get();
return $data;
}
I see a couple of issues:
You should be using $this->db->where(), instead of $this->db->get_where(). get_where() executes the query immediately.
$this->db->get_where('user_id', $id);
Also the first argument of $this->db->join() should only be the table name, excluding the field.
$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
And you're returning $data which is just an empty array(). You would need to pass the query results to $data like this:
$data = $record->result_array();
get_where executes the query. So, your join is its own query, which doesn't work.
You need to break get_where into where and from.
Also, in MySQL, you JOIN a table, not a field. If you want that field, add it to the SELECT.
$this->db->select($this->profiles_table.'.*');
$this->db->select($this->accounts_table.'.email,'.$this->accounts_table.'.username');
$this->db->from($this->profiles_table);
$this->db->where('user_id', $id);
$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
$data = $this->db->get();
NOTE: $this->db->get() returns a query object, you need to use result or row to get the data.
I think you've a mistake:
$this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
First parameter should a table NOT a field: $this->accounts_table.'.email' is wrong IMHO. Or only a typo :)

Retrieve session data Codeigniter

I'm working on a messaging system and want the user's userid to be posted to the database along with the message. Right now, the message is posting to the database, but with a user ID of 0.
How can I get the user ID from the session data to post to the database along with the message? Sidenote: I'm using Tank Auth for authentication. (From the mysql side, user_id in the message table is a foreign key referencing id in the users table).
Controller
function index() {
if ($this->input->post('submit')) {
$id = $this->input->post('user_id');
$message = $this->input->post('message');
$this->load->model('message_model');
$this->message_model->addPost($id, $message);
}
}
Model
function addMessage($id, $message) {
$data = array(
'user_id' => $id,
'message' => $message
);
$this->db->insert('message', $data);
}
For tank_auth, get the user_id using the following, and then assign that to your sessions
$user_id = $this->tank_auth->get_user_id();
Taken directly from CI's documentation:
Retrieving Session Data
Any piece of information from the session array is available using the
following function:
$this->session->userdata('item');
Where item is the array index
corresponding to the item you wish to fetch. For example, to fetch the
session ID you will do this:
$session_id = $this->session->userdata('session_id');
Note: The
function returns FALSE (boolean) if the item you are trying to access
does not exist.
So, if you have a piece of session data named user_id, you would access it like this:
$user_id = $this->session->userdata('user_id');