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');
Related
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 .
My app's goal is to schedule posts through a franchise to its franchised.
The HQ schedules a post for a certain date and time, with text and potential image.
It creates the post with all necessary information in the database for each franchised(id, franchise_id, user_id, text, image, network, post_id)
post_id contains an id that is the same for each row that are completely identical besides the franchise_id.
When I add a post, it works well. But when editing, since it gets the ID of the post, it'll only edit the post that matches the id.
And that is fine when it is a franchised, it will then change the post_id to a custom value, and will be independent to the others.
But when it's the HQ(superadmin)logged in, I want him to edit all that matches the selected one by post_id.
Query builder is not something I'm used to and sometimes I thought about dropping it for standard SQL, but if it's there it's for a reason, so I would like your help in solving this with Cakephp's query builder.
public function edit($id = null){
$event = $this->Events->get($id);
if ($this->request->is(['post', 'put'])) {
$event = $this->Events->patchEntity($event, $this->request->data,['associated' => ['Networks'], ]);
if($isuper == 'true'){//if logged in user is superadmin
}else{
$event->user_id = $this->Auth->user('id');
}
if ($this->Events->save($event)) {
$this->Flash->success(__('your post has been updated'));
return $this->redirect(
[
'action' => 'index',
date('Y', $event->date->getTimestamp()),
date('m', $event->date->getTimestamp()),
$event->company_id
]
);
}
$this->Flash->error(__('unable to update your post'));
}
$this->set('event', $event);
$this->layout = 'ajax';
}
You could try making bulk updates using updateAll
Something like:
$this->Events->updateAll(
['field' => true], // whatever fields you are updating
['post_id' => 'some_id'] // the selected post_id
);
I am new to laravel. I am working on a laravel 5 app and I am stuck here. I have 2 models as such:
class Message extends Eloquent{
public function user()
{
return $this->belongsTo('App\User', 'from');
}
public function users()
{
return $this->belongsToMany('App\User')->withPivot('status');
}
}
class User extends Eloquent {
public function messages()
{
return $this->hasMany('App\Message', 'from');
}
public function receive_messages() {
return $this->belongsToMany('App\Message')->withPivot('status');
}
}
There exist a many-to-many relationship between Message and User giving me a pivot table as such:
Table Name: message_user
Colums:
message_id
user_id
status
I have an SQL query as such:
update message_user
set status = 1
where user_id = 4 and message_id in (select id from messages where message_id = 123)
How can I translate this query to the laravel equivalent?
The code below solved my problem:
$messages = Message::where('message_id', $id)->get();
foreach($messages as $message)
$message->users()->updateExistingPivot($user, array('status' => 1), false);
You may use one of these two functions, sync() attach() and the difference in a nutshell is that Sync will get array as its first argument and sync it with pivot table (remove and add the passed keys in your array) which means if you got 3,2,1 as valued within your junction table, and passed sync with values of, 3,4,2, sync automatically will remove value 1 and add the value 4 for you. where Attach will take single ID value
The GIST: if you want to add extra values to your junction table, pass it as the second argument to sync() like so:
$message = Messages::find(123);
$user = User::find(4);
// using attach() for single message
$user->message()->attach($message->id, [
'status' => 1
]);
$message2 = Messages::find(456); // for testing
// using sync() for multiple messages
$user->message()->sync([
$message->id => [
'status' => 1
],
$message2->id => [
'status' => 1
],
]);
Here is a small example of how to update the pivot table column
$query = Classes::query();
$query = $query->with('trainees')
->where('user_id', Auth::id())
->find($input['classId']);
foreach ($query->trainees as $trainee) {
$trainee->pivot->status = 1 //your column;
$trainee->pivot->save();
}
Note: make sure your relation data must in an array
Hope its help you :)
happy coding
Laravel 5.8
First, allow your pivot columns to be searchable by chaining the withPivot method to your belongsToMany
Copied from my own code to save time
// I have 3 columns in my Pivot table which I use in a many-to-many and one-to-many-through scenarios
$task = $user->goalobjectives()->where(['goal_objective_id'=>$goal_objective_id,'goal_obj_add_id'=>$goal_obj_add_id])->first(); //get the first record
$task->pivot->goal_objective_id = $new; //change your col to a new value
$task->pivot->save(); //save
The caveat is that your pivot table needs to have a primary 'id' key.
If you don't want that then you can try the following:
$tasks=$user->posts()->where(['posts_id'=>$posts_id,'expires'=>true])->get()->pluck('id'); // get a collection of your pivot table data tied to this user
$key=join(",",array_keys($tasks->toArray(),$valueYouWantToRemove));
$tasks->splice($key,1,$newValueYouWantToInsert);
$c = array_fill(0,$tasks->count(),['expires'=>true]); //make an array containing your pivot data
$newArray=$tasks->combine($c) //combine the 2 arrays as keys and values
$user->posts()->sync($newArray); //your pivot table now contains only the values you want
4th July Update Update to above snippet.
//Ideally, you should do a check see if this user is new
//and if he already has data saved in the junction table
//or are we working with a brand new user
$count = $user->goalobjectives->where('pivot.goal_obj_add_id',$request->record)->count();
//if true, we retrieve all the ids in the junction table
//where the additional pivot column matches that which we want to update
if($count) {
$ids = $user->goalobjectives->where('pivot.goal_obj_add_id',$request->record)->pluck('id');
//convert to array
$exists = $ids->toArray();
//if user exists and both saved and input data are exactly the same
//there is no need
//to update and we redirect user back
if(array_sum($inputArray) == array_sum($exists)) {
//redirect user back
}
//else we update junction table with a private function
//called 'attachToUser'
$res = $this->attachToUser($user, $inputArray, $ids, $request->record);
}//end if
elseif(!$count) {
//we are working with a new user
//we build an array. The third pivot column must have equal rows as
//user input array
$fill = array_fill(0,count($inputArray),['goal_obj_add_id'=>$request->record]);
//combine third pivot column with user input
$new = array_combine($inputArray,$fill);
//junction table updated with 'user_id','goal_objective_id','goal_obj_add_id'
$res = $user->goalobjectives()->attach($new);
//redirect user if success
}
//our private function which takes care of updating the pivot table
private function attachToUser(User $user, $userData, $storedData, $record) {
//find the saved data which must not be deleted using intersect method
$intersect = $storedData->intersect($userData);
if($intersect->count()) {
//we reject any data from the user input that already exists in the database
$extra = collect($userData)->reject(function($value,$key)use($intersect){
return in_array($value,$intersect->toArray());
});
//merge the old and new data
$merge = $intersect->merge($extra);
//same as above we build a new input array
$recArray = array_fill(0,$merge->count(),['goal_obj_add_id'=>$record]);
//same as above, combine them and form a new array
$new = $merge->combine($recArray);
//our new array now contains old data that was originally saved
//so we must remove old data linked to this user
// and the pivot record to prevent duplicates
$storedArray = $storedData->toArray();
$user->goalobjectives()->wherePivot('goal_obj_add_id',$record)->detach($storedArray);
//this will save the new array without detaching
//other data previously saved by this user
$res = $user->goalobjectives()->wherePivot('goal_obj_add_id',$record)->syncWithoutDetaching($new);
}//end if
//we are not working with a new user
//but input array is totally different from saved data
//meaning its new data
elseif(!$intersect->count()) {
$recArray = array_fill(0,count($userData),['goal_obj_add_id'=>$record]);
$new = $storedData->combine($recArray);
$res = $user->goalobjectives()->wherePivot('goal_obj_add_id',$record)->syncWithoutDetaching($new);
}
//none of the above we return false
return !!$res;
}//end attachToUser function
This will work for pivot table which doesn't have a primary auto increment id. without a auto increment id, user cannot update,insert,delete any row in the pivot table by accessing it directly.
For Updating your pivot table you can use updateExistingPivot method.
I have a webapp where a user can log in and see a dashboard with some data. I'm using APIary for mock data and in my Postgres Database each of my users have an ID. These ID's are also used in the APIary JSON file with relevant information.
I'm using REST::Client and JSON to connect so for example the url for the user's dashboard is: "/user/dashboard/12345" (in Apiary)
and in the database there is a user with the ID "12345".
How can I make it so when the user logs in, their ID is used to pull the data that is relevant to them? (/user/dashboard/{id})? Any documentation or advice would be much appreciated!
The docs of Dancer2::Plugin::Auth::Extensible are showing one part of what you need to do already. In short, save the user ID in the session. I took part of code in the doc and added the session.
post '/login' => sub {
my ($success, $realm) = authenticate_user(
params->{username}, params->{password}
);
if ($success) {
# we are saving your user ID to the session here
session logged_in_user => params->{username};
session logged_in_user_realm => $realm;
} else {
# authentication failed
}
};
get '/dashboard' => sub {
my $client = REST::Client->new();
# ... and now we use the user ID from the session to get the
# from the webservice
$client->GET( $apiary . '/user/dashboard/' . session('logged_in_user') );
my $data = $client->responseContent();
# do stuff with $data
};
For those who want to know what I ended up doing:
Dancer2::Plugin::Auth::Extensible has
$user = logged_in_user();
When I printed this it showed me a hash of all the values that user had in the database including the additional ID I had. So I accessed the id with
my $user_id = $user->{user_id};
And appended $user_id to the end of the url!
Question:
How to update the changed username in session variable without logout or session destroy ?
For Example:
I am login with username "Ram" and this username storing in session variable User_Name,after logged in i am changing my username "Ram" into "Kumar". So this newly changed username should get updated in session variable User_Name automatically without logout from my account.
Sample Controller Code for Login:
function check_database($password)
{
// Field validation succeeded. Validate against database
$username = $this->input->post('username');
// query the database
$result = $this->civic_soft_model->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'UID' => $row->UID,
'User_Name' => $row->User_Name,
'User_Type' => $row->User_Type,
'User_OTP' => $row->User_OTP
// 'Login_Status' => $row->Login_Status
// 'Node_Id' => $row->Node_Id
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
NOTE:
I am using PHP,MySQL and CodeIgniter MVC Framework.
Please Help Me Friends...
I actually see what the problem is now. You are setting 'logged_in' to be an array. Not sure if that's common, but what I usually do is set 'logged_in' as a boolean and I set userdata the data that I need in another array.
However, for you case you can try this:
$newUserData = $this->session->userdata('logged_in');
if (is_array($newUserData)) {
$newUserData['User_Name'] = $new_username;
$this->session->set_userdata('logged_in', $newUserData);
}
For better usability, I would addd a function to $this->civic_soft_model called "updateUser" or something of that nature. And when that function is called, you can update all of the session data that you need to.
Insert this function to your controller and call it whenever there is an update made on the users information.
//$new_username : the username inputted by user when he is trying to update his account
function update_session($new_username){
$this->session->set_userdata('User_Name', $new_username);
}