How to update the updated_at column when the user logs in? - mysql

I'm trying to update the updated_at column to the current time, each time a user logs in.
But I get the following error:
InvalidArgumentException A four digit year could not be found Data missing
PHP
$input = Input::all();
$remember = (Input::has('remember')) ? true : false;
$auth = Auth::attempt([
'username' => $input['username'],
'password' => $input['password'],
'active' => 1
],$remember
);
if ($auth)
{
$user = Auth::user();
$user->updated_at = DB::raw('NOW()');
$user->save();
if ($user->userType==1)
{
return Redirect::intended('admin');
}
elseif ($user->userType==2)
{
return Redirect::intended('corporate');
}
elseif ($user->userType==3)
{
return Redirect::intended('trainer');
}
elseif ($user->userType==4)
{
return Redirect::intended('user');
}
}

You can use the Eloquent method touch() for this:
//instead of
$user->updated_at = DB::raw('NOW()');
$user->save();
// simply this:
$user->touch();

For one I would not use the updated_at column as that's the default timestamps name.
You would be better of with last_login
And just use the PHP date method.
$user->updated_at = date('Y-m-d G:i:s');
Hope this helps.

I think you're accidentally assigning a value instead of using array syntax. eg:
Model::create([
'key'='val'
]);
instead of:
Model::create([
'key'=>'val'
]);

Related

How to combine four queries in laravel?

I have draws on my site, in order to take part in the draw, you need to do a certain action per day. And there is a code that checks it all:
$date = Carbon::today();
$sta = \DB::table('ets')->where('user_id', $this->user->id)->where('created_at', '>=', $date)->get();
$sta = \DB::table('ets_1x1')->where('user_id', $this->user->id)->where('created_at', '>=', $date)->get();
$sta = \DB::table('ets_low')->where('user_id', $this->user->id)->where('created_at', '>=',$date)->get();
$sta = \DB::table('ets_duel')->where('user_id', $this->user->id)->where('created_at', '>=', $date)->get();
if ($sta == NULL) {
return response()->json(['status' => 'error', 'msg' => 'Error']);
}
This code checks if there is a user record in 4 possible tables. I made an entry in the table ets_1x1, but still I can’t take part, because the error seemed to not find me in the database. I removed all the tables and left only ets_1x1 and I was accepted into the drawing.
As I understand it, the value is taken from the last request. How can I combine a query into 1 and do a check on these 4 tables?
UPD:
I also tried to give new names to the variables and display the response code differently, now participation in the drawing is accepted from all people, even from those who have not fulfilled the conditions, now it looks:
if(!empty($sta_1) || !empty($sta_2) || !empty($sta_3) || !empty($sta_4)) {
return response()->json(['status' => 'error', 'msg' => 'Error']);
}
Where my mistake?
That code is not going to work because:
The first piece of code will evaluate only the last request (and in consecuence, only if there is any existent user on the last table only).
The second piece of code is not being evaluated correctly, you are running empty function on a Laravel collection.
Why don't you try this? I think it should work:
$date = Carbon::now();
$userExists = false;
$tables = ['ets', 'ets_1x1', 'ets_low', 'ets_duel'];
foreach ($tables as $tableName) {
$result = \DB::table($tableName)
->where('user_id', $this->user->id)
->where('created_at', '>=', $date)
->get()
;
if ($result->isNotEmpty()) {
$userExists = true;
break;
}
}
if (!$userExists) {
return response()->json(['status' => 'error', 'msg' => 'Error']);
}

Last inserted id Inside transaction with Lumen/Laravel

How can I get the last inserted id
I use the following code which works:
DB::insert("INSERT INTO members (name,email)values($name,$email)");
$lastID = DB::getPdo() -> lastInsertId();
But the following code doesn't give me the last inserted id.
DB::transaction(function () {
$result = DB::insert("INSERT INTO members (name,email)values($name,$email)");
$lastID = DB::getPdo() -> lastInsertId();
}, 5);
return $lastID;
Even when I use the variable($lastID) outside the transaction it still doesn't work.
What am I doing wrong here?
When using the query builder, Laravel has the function insertGetId which inserts the row and returns the newly created id.
$lastid = DB::table('members')->insertGetId(['name' => $name, 'email' => $email]);
Please see sample code below. Hope it helps.
public function testModel($data) {
$id = DB::transaction(function() use ($data) {
$record_id = DB::table('users')->insertGetId($data);
DB::update('update users set votes = 100 where name = ?', ['John']);
return $record_id;
});
return $id; // this will return the last inserted id which is the $record_id inside the DB::transaction
}
You can get it easily:
$last_id = DB::table('members')->insertGetId(['name => $name, 'email => $email]);
this worked for me
public function testModel($data) {
$last_id = DB::transaction(function() use ($data) {
Table::create($data);
return DB::getPdo()->lastInsertId();
});
return $last_id; // this will return the last inserted id
}
The trick should be quite simple if you use Model. Let's assume you've Member model. So when you try to insert record it returns the inserted record in response.
/** Insert record **/
$member = Member::create(['name' => $name, 'email' => $email])
/** your last inserted id will be in $member **/
$lastInsertedId = $member->id
Hope this works for you.

How to force data update on laravel validation custom unique

I'm new in laravel. I have a table with menu_id and title I tried to make this title field unique when have the same menu_id. I found the solution here
But I got problem when update it. Can anyone help please?
My code
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// Check the table and return true only if there are no entries matching
// both the first field name and the user input value as well as
// the second field name and the second field value
return \DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});
public function updateSubmenu( Request $request) {
$this->validate( $request, [
'menu_id' => 'required',
'title' => 'required|unique_custom:posts,title,menu_id,'.$request->menu_id,
'order_by' => 'required|integer',
'description' => 'required'
],
[
'title.unique_custom' => 'This title already token'
]
);
}
Can you explain what problem have you got on update? Some exception?
Edit:
If you couldn't update record if title not changes, you need to add one condition to Validator:
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// If old value not changed, don't check its unique.
$current = \DB::table($table)->where('title')->first();
if( $current->{$field} == $value) {
return true;
}
return \DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});

how to get recently affected rows attribute in model of codeigniter

primary key of title table is id and it is an auto-increment when I insert data to the table I need to return the id of currently inserted row.
my model function is,
function addDate($x, $y, $z) {
$sql = "INSERT INTO title (title,no,user) VALUES ('$x','$y','$z')";
$query = $this->db->query($sql );
if($this->db->affected_rows() > 0) {
return "ok";
} else {
return "err";
}
}
Please help me on this.
You are wrong. In your function you are getting these three parameters ($x, $y, $z) But in code you are Inserting ('$t','$n','$a')(Question is edited)
Use $this->db->insert_id() to get last insert id
Try this
function addDate($x, $y, $z) {
$data = array(
'title' => $x ,
'no' => $y ,
'user' => $z
);
if(!$this->db->insert('title', $data)){
return FALSE ;
}
else{
$lastId = $this->db->insert_id(); # add this
return $lastId;
}
}
FYI: Don't use $x, $y, $z. use meaningful names like $title, $no, $user
Codeigniter Active Record Class Version 2.2.0

insert if not exists Codeigniter

my controller:
function getFeed()
{
$feed_url = $this->input->get("url");
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
foreach($x->channel->item as $entry) {
$feeds[] = array(
'title' => (string)$entry->title,
'url'=> (string)$entry->link,
'username' => $this->session->userdata('username')
);
$this->load->model('membership_model');
$this->membership_model->feeds($feeds);
}
Model:
function feeds($feeds_data)
{
$this->db->insert_batch('feeds', $feeds_data);
}
Is there a function to insert if only the row doesn't exists in the table? I have a table with 4 column : id,title,url,username. I have an anchor when i click him it calls geFeed function and insert the info into table. But i want to insert only if not exists.
I had the same challenge, so i eventually come up with a function which might be helpful to you.
function safe_update_batch($table_name,$records,$filter_field)
{
$filters=array();
foreach($records as $record)$filters[]=$record[$filter_field];
$this->db->query("SET SESSION group_concat_max_len=10000000");
$query=$this->db->select("GROUP_CONCAT($filter_field) AS existing_keys",FALSE)->where_in($filter_field, $filters)->get($table_name);
$row=$query->row();
$found_fields=explode(',',$row->existing_keys);
$insert_batch=array();
$update_batch=array();
foreach($records as $record)
{
if(in_array($record[$filter_field],$found_fields))$update_batch[]=$record;
else $insert_batch[]=$record;
}
if(!empty($insert_batch))$this->db->insert_batch($table_name,$insert_batch);
if(!empty($update_batch))$this->db->update_batch($table_name,$update_batch,$filter_field);
}
//sample usage
$this->safe_update_batch('feeds', $feeds_data,'title');
You can try this in your model!!
function insertClient($array)
{
$this->db->from('MyTable');
$this->db->where('Id', $array['Id']);
$query = $this->db->get();
if($query->num_rows() != 0){
$data = array(
'name'=>$array['name'],
'phone'=>$array['phone'],
'email'=>$array['email']
);
$this->db->where('Id', $array['Id']);
$this->db->update('CLIENTS', $data);
}else{
$data = array(
'name'=>$array['name'],
'phone'=>$array['phone'],
'email'=>$array['email']
);
$this->db->insert('CLIENTS',$data);
}
}
In controller:
$this->site_model->insertClient($_POST);
Sadly if you are using the active record class an INSERT IF NOT EXISTS function doesn't exist. You could try
Extending the active record class (easier said than done)
You could set indexes on certain columns as UNIQUE so that MySQL will check to see if it already exists
You could do some kind of SELECT before your INSERT to determine if the record is already there
For the queries where you need to do INSERT IF NOT EXISTS do $this->db->query('INSERT IF NOT EXISTS...')
function getFeed()
{
// Load the model up here - otherwise you are loading it multiple times
$this->load->model('membership_model');
$feed_url = $this->input->get("url");
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
foreach($x->channel->item as $entry) {
// check if the feed is unique, if true then add to array
if( $this->membership_model->singleFeedIsUnique($entry) == TRUE ){
$feeds[] = array(
'title' => (string)$entry->title,
'url'=> (string)$entry->link,
'username' => $this->session->userdata('username')); }
} //foreach
// check to make sure we got any feeds with isset()
// if yes, then add them
if (isset($feeds)){ $this->membership_model->feeds($feeds); }
}
You can try this in your model and leave you controller without changes
function feeds($feeds_data)
{
$data = array(
title => $feeds_data[0],
url => $feeds_data[1],
username => $feeds_data[2]
);
$this->db->select('*');
$this->db->from('mytable');
$this->db->where('title',$feeds_data[0]);//you can use another field
if ($this->db->count_all_results() == 0) {
$query = $this->db->insert('mytable', $data);//insert data
} else {
$query = $this->db->update('mytable', $data, array('title'=>$feeds_data[0]));//update with the condition where title exist
}
}
you can check the id if you have it, adding in the data array and use it to check if exist