I want to create uniqueid based on timestamps in laravel.
In laravel, Timestamps become 2 column, namely created_at and updated_at.
like this timestamps laravel
I want to combine created_at and updated_at column for unique id without dash (-) and (:).
sample output (for first row in screenshot): 2016091510453920160915104539
I used this code for $transid column:
public function insertFund($request,$lender, $type)
{
$transid = timestamp();
$fund = $this->fund->create([
'transid' => $transid
]);
return $fund;
}
But, i get error when submit.
is it possible to write code for this here?
Thanks in Advance.
i try this, and it works for me
$now = Carbon::now();
$unique_code = $now->format('YmdHisu')
the output is
20180410171800873514
if you parse you can see 2018 04 10 17:18:00 873514
I don't know what exactly you are trying to do. I understood that you want to create a record and fill the transid with concatenated timestamps.
The timestamps before the are empty as the record hasn't created yet.
In your case i would create the record and after that i would get the timestamps and update the same record.
Example code:
$fund = Fund::create($input);
$transid = $fund->created_at.$fund->updated_at;
$fund->transid = $transid;
$fund->update();
If this is not what you are trying to do , provide more information in order to help.
Related
I'm creating database notifications. I have 2 Notification classes:
InterviewRequestReceived.php:
$user = Auth::user();
$interviewRequestReceived = InterviewRequestsReceived::latest()->where('user_id', $user->id)->get();
return [
'date_time1' => $interviewRequestReceived[$interviewRequestReceived->count() - 1]->latest()->get('date_time1'),
'date_time2' => $interviewRequestReceived[$interviewRequestReceived->count() - 1]->latest()->get('date_time2')
];
and InterviewRequestSent.php:
public function toDatabase($notifiable)
{
$user = Auth::user();
$interviewRequestSent = InterviewRequestsSent::latest()->where('user_id', $user->id)->get();
return [
'date_time1' => $interviewRequestSent[$interviewRequestSent->count() - 1]->latest()->get('date_time1'),
'date_time2' => $interviewRequestSent[$interviewRequestSent->count() - 1]->latest()->get('date_time2')
];
}
I have 3 tables. interview_requests_receiveds, interview_requests_sents and I created the notifications table and migrated.
On my form I have 2 options for datetime fields, so Employers can choose 2 possible date and times that would work for them to interview a candidate.
My form is working.
My notifications are working except it's inserting all of the logged in Users' date and times, instead of just the last inserted record.
I'm trying to use latest(), but it's not working.
As per Laravel Documentation
The latest and oldest methods allow you to easily order results
by date. By default, result will be ordered by the created_at
column. Or, you may pass the column name that you wish to sort by
If you want to use latest then instead of get() use first() function:
If there is already created_at column in your table then
$interviewRequestSent = InterviewRequestsSent::latest()->where('user_id', $user->id)->first();
OR
Assuming you want to get last record based on id column
$interviewRequestSent = InterviewRequestsSent::latest('id')->where('user_id', $user->id)->first();
Or you can get the last record using any below methods
InterviewRequestsSent::where('user_id', $user->id)->last();
OR
InterviewRequestsSent::where('user_id', $user->id)->orderBy('id', 'desc')->first();`
Reference:
Laravel -> Query Builder -> latest method
i want to get difference between two values. i get my last entered value in bill no and get difference with input value.
this is my controller function model
$restPaymentSales = DB::table('sales')
->select('rest_payment')
->where('bill_no', $request->input('bill_no'))
->orderBy('created_at', 'desc')
->first();
$payment = $request->input('payment');
$doubleVal = doubleval($payment);
and i wrote calculation like this
$restSales = $restPaymentSales->child['rest_payment'] - $doubleVal;
but it shows me this error
Trying to get property of non-object
my table row like this
rest_payment -> double(11,2)
how can i fix this issue. basically i want to get difference between table last value order by date and input value.
Update your calculation from:
$restSales = $restPaymentSales->child['rest_payment'] - $doubleVal;
TO
$restSales = $restPaymentSales->rest_payment - $doubleVal;
I am trying to get user login activity per month and then to show it in statistic in a bar chat. But the problem i am facing is that its not giving me any data. I will share my code first it will easier to explain my problem
My LoginActivity Model
class LogActivity extends Model
{
protected $table = 'laravel_logger_activity';
public function logActivity(){
$videoPerMonth = array();
for ($i=1; $i<=12; $i++){
$age= 12 - $i;
$userPerMonth[$i] = count(LogActivity::whereNotIn('userId', [1])->whereMonth('created_at', '=', date('n') -$age)->get());
}
}
}
In this i do get user's activity per month but this is not accurate because being the first month if u subtract 12 value goes to negative. And i dont get actual reults.
So, after reading few articles i changed my code to this
$userPerMonth =count( LogActivity::whereNotIn('userId', [1])->whereMonth('created_at', '>=', Carbon::now()->subMonth(12))->get());
return json_encode($userPerMonth);
But this returns empty.What shall i do ?
I want to get data by month vs activity
For example nov 2017 : 300 , dec 2017:800,jan 01 2018:100
Something like that so i can put in bar chat
Can anyone please help me with this
Thanks
I would be tempted to tackle this in a different way, instead of trying to get the user's login activity per month in a loop. I would get the user's login activity for a date range such as a year. This would result in one SQL query being run rather than 12 per user. Once you have the data you can loop through the results and sort them into an array or collection.
Or you could do it as the equivalent of this SQL statement.
SELECT COUNT(*) as login_num, DATE_FORMAT(created, '%m') as login_month, user_id
FROM login_tokens
WHERE created_at >= '2017-01-01 00:00:01' AND created_at <= '2017-12-31 23:59:59'
GROUP BY user_id, login_month
I think to do this in eloquent you would need to do the following;
$logActivity = LogActivity::where(‘created_at’, ‘>=’, ‘2017-01-01 00:00:01’)
->where(‘created’, ‘<=’, ’23:59:59’)
->select(\DB:raw(‘COUNT(*) as login_num, DATE_FORMAT(created, '%m') as login_month, user_id’))
->groupBy(‘user_id’)
->groupBy(‘login_month’)
->get();
Downside to this approach is you're having to put in knowledge of the SQL language, which could differ from MySql, to SQLite, MSSQL etc.
A useful tip if you remove the get() and replace it with toSql() you can echo out the query.
echo LogActivity::where(‘created_at’, ‘>=’, ‘2017-01-01 00:00:01’)
->where(‘created’, ‘<=’, ’23:59:59’)
->select(\DB:raw(‘COUNT(*) as login_num, DATE_FORMAT(created, '%m') as login_month, user_id’))
->groupBy(‘user_id’)
->groupBy(‘login_month’)
->toSql();
dd();
Hope that helps a bit.
I've knocked together a simple class that is more or less what I think you're after. Please note that the use statements are probably not quite right and I've not run this code, so use it as an example. Basically what I've done here is get the current date and work out the previous year from now.
That is then used to select the data from the database within getActivity method. An empty array is created $dateRange for storing the results in with the keys being the year and the month i.e. 2018-02, 2018-01, 2017-12, 2017-11 and so on.
Next I'm doing a simple check to see if we actually have any results from the database because if there are no results then the logins would be 0 for each month.
Then get a date range, okay I've swapped back to standard PHP date interval here as I don't know the Carbon syntax of the top of my head, but as Carbon extends PHP's DateTime it probably should work. However, it may need some tweaking here as well. So get the date range between the two dates by a monthly interval.
Then loop through this date range, use the $hasLoginActivity variable we defined earlier and if that's false add the date range formatted to year-month as the key and the value to zero.
If we have results then add the date range with the same formatting and get the data from the results. As we have returned a collection from Laravel's ORM we should be able to where on it again, see Collections docs. Store this to a variable and check to see if we have results before trying to access the property, else set to zero. You might be able to skip this and access it like $loginActivity->where('login_year_month', $date->format('Y-m'))->login_num; but I can't remember of the top of my head if this causes an error trying to access property on a null value.
I hope this helps.
<?php
use Carbon;
use DateInterval;
use DatePeriod;
use LogActivity as LogActivityModel;
class LogActivity
{
public function annualActivity(): array
{
// Get the current date/time and get a year from now.
$now = new Carbon();
$aYearAgo = $now->clone()->subYears(1);
// Get any login activity from the last year to now.
$loginActivity = $this->getActivity($aYearAgo, $now);
$dateRange = [];
$hasLoginActvity = $loginActivity->count();
// Get a date range from a year ago to now and loop through them.
foreach ($this->getDateRange($aYearAgo, $now) as $date) {
// If we there were no results, then just create the array with a result set of zero.
if (! $hasLoginActvity) {
$dateRange[$date->format('Y-m')] = 0;
continue;
}
$monthActivity = $loginActivity->where('login_year_month', $date->format('Y-m'));
$loginCount = $monthActivity ? $monthActivity->login-num : 0;
// Add to the array the date YYYY-MM as the key i.e. 2018-02 and search the collection for the same date.
$dateRange[$date->format('Y-m')] = $loginCount;
}
// Return the array date with the year and month as the key and a integer as the value.
return $dateRange;
}
private function getActivity(Carbon $aYearAgo, Carbon $now)
{
return LogActivityModel::where(‘created_at’, ‘>=’, $aYearAgo->format('Y-m-d H:i:s'))
->where(‘created_at’, ‘<=’, $now->format('Y-m-d H:i:s'))
->select(\DB:raw(‘COUNT(*) as login_num, DATE_FORMAT(created, '%Y-%m') as login_year_month, user_id’))
->groupBy(‘user_id’)
->groupBy(‘login_month’)
->all();
}
private function getDateRange($from, $to)
{
// Get a the date range between the two dates with an interval of a month.
return new DatePeriod($from, new DateInterval('P1M') ,$to);
}
}
I am working on an application which uses Laravel and Eloquent that determines whether something (a job) has not been completed on time. This is stored as a DATE within the table. E.g. 2016-07-18
I am trying to get all the records where todays date is greater than the "completed_date" stored inside the table.
Here is what I have tried:
$id = \Auth::user()->id;
$now = \Carbon\Carbon::today();
$jobs = Job::whereHas('manager', function ($user) use ($id) {
$user->where('users.id', '=', $id);
})->where('complete_date', '>', $now)->get();
The issue is that it's still retrieving records that are in the future. For example, the record it returns, I checked the table and the "complete_date" is 2016-08-31
Any ideas please?
Your $now variable is a Carbon object, not a date.
You have to convert the object to a date:
$now = \Carbon\Carbon::now()->format('Y-m-d');
Then you have to use this variable in your model query.
I have a table with the following columns.
id (profile id) int(10)
viewer (visitor id) int(10)
ip (visitor ip) int(10)
ts (unix timestamp) int(10)
Now, I want to query if the visitor x, has visited profile y today.
My thought is that, I want to do something like this.
public function hasVisitToday(Profile $profile)
{
$dt = Carbon::now();
if(ViewTrack::where('id', $profile)->where('viewer', $visitor)->whereDate('ts', $dt->today())->first())
return true;
return false;
}
The project use Laravel 5.1, and one of the main problems is, that the database store the timestamp as „unix timestamp“ in a int column and not as timestamp column.
And I'm searching for the best way to handle this.
Thank's Zoe,
but i choose the whereBetween statement and this is my solution.
$carbon = Carbon::now();
$start = Carbon::now()->startOfDay();
$visit = ViewTrack::where('id', $this->id)
->where('viewer', $visitor->id)
->whereBetween('ts', [$start->timestamp , $carbon->timestamp])
->get();
if($visit->count() > 0)
return true;
return false;
if(ViewTrack::where('id', $profile)
->where('viewer', $visitor)
->where('ts', '>=', $dt->startOfDay()->timestamp())
->count())
You should be able to compare Unix timestamps if they're both in the same format.
I tend towards agreeing with the above comment that I'd rather have it in a human readable format so that I can see if I'm getting any weird dates.
If you get any funny business make sure your server, MySQL server and laravel config timezones all match.