how to select one month back records from data base in laravel - laravel-5

how select one month back records from current date from database in laravel. I am trying this code.
This is controller code.
class LoginHistoryController extends Controller {
public function index()
{
$login_history = LoginHistory::where('login_date','BETWEEN', '(CURDATE() -
INTERVAL 10 DAY) AND CURDATE()' )->get();
}
}
but i am getting error.

I will have a approach something like this. First I will calculate the date like
$today = date('Y-m-d');
$date = date_create($today);
date_sub($date, date_interval_create_from_date_string("30 days"));
$beforeOneMonth = date_format($date, "Y-m-d");
You should have the intended value in $beforeOneMonth by now. Now you can compare it in anyway you like whether you use IN operator or >=. For eg.
$login_history = LoginHistory::where('login_date','>=', $beforeOneMonth)->get();
Give it a try. If you are storing date in some other format, you can do your own tricks to format the date and do the thing

Another way to do it would be with whereRaw:
$login_history = LoginHistory::whereRaw(
'login_date BETWEEN (CURDATE() - INTERVAL 10 DAY) AND CURDATE()'
)->get();
Note that whereRaw has the side effect of making your code less portable since you're using SQL that might be specific to your database server. But sometimes you just can't do what you would like using the query builder.

Related

Show list of registered users base on current month using laravel

Im new to laravel and im tryin to learn the fundamentals of it. My question is how can I display all the registered users that is registered only on the current month.
$from = now()->startOfMonth(); // first date of the current month
$to = now();
$usersRegisteredThisMonth = User::whereBetween('created_at', [$from, $to])->get();
There is a simple way of doing it.
Just use this code
User::whereMonth('created_at', now()->month) // checking if the month of created_at is current month
->whereYear('created_at', now()->year) // checking if the year of created_at is current year
->get();
This line will give you Users from current month.
Nobody explained that these queries might be put in user model with local scope scopeWith magic method. I assume you read docs from top to bottom.
Simple example:
public function scopeRegisteredLastMonth($query){ return $query->whereBetween... }
Laravel Local Scope
You can specyficy additional arguments for this method.
The final call in controller will look like this:
$lastMonthUsers = User::registeredLastMonth()->get();
This function should be set to something like 'public function withRegisteredBetween($query, $date_start, $date_end) and return query based on date range.
PS: Don't use DB:: when you can use Model::method() or Model::query()->method()
PS2: for date management I advise you to install carbon, it's an additional addon - sometimes it's easy, sometimes not, overall not bad.
You could use the users table with a whereBetween clause like this:
$from = date('2022-01-05 00:00:00');
$to = date('2022-31-05 00:00:00');
$usersRegisteredThisMonth = DB::table('users')->
whereBetween('created_at', [$from, $to])->get();

Laravel - different formats for date/time query

I am learning Laravel and I have some small problem on controllers - when I use DB, the query returns date time without timezone but if I use model, the query returns full datetime.
public function test($switch)
{
//return "YYYY-MM-DDThh:mm:ss.000000Z"
if ($switch) return Position::select('id','created_at')->orderBy('id')->get();
// return "YYYY-MM-DD hh:mm:ss"
return DB::table('positions')->select('id','created_at')->orderBy('id')->get();
}
Why? What I need to dof I want "YYYY-MM-DDThh:mm:ss.000000Z" on both cases?
Thanks for solution.
thanks for advice
You should use the DB::raw
The following statement will convert the datetime value created_at from +00:00 timezone to +10:00 timezone.
You can try this
return DB::table('positions')->select(DB::raw('id',CONVERT_TZ('created_at','+00:00','+10:00'))->orderBy('id')->get();
you can set your timezone that you wants to convert it
They are the same data, probably just different classes of date and you can always format your date. Laravel utilizes Carbon date library which is excellent and should be used primarily.
If you try to print out your date class with get_class() for Eloquent Position created_at, you probably got Carbon and DB::table('positions') created_at, you probably got DateTime and that's why the value looks different (but you still got the same date).
If you want to convert your DateTime to Carbon, you can do
$newDate = new \Carbon\Carbon($position->created_at)
Thanks Anurat,
I realized this fact shortly after sending the previous question.
... but there is another 'issue' - both times are my local time - time in "YYYY-MM-DDThh:mm:ss.000000Z" is not UTC time as I expected.
I changed my function:
public function test($switch = false)
{
$data = Position::selectRaw('id, created_at, UNIX_TIMESTAMP(created_at) unix')->orderBy('id')->get();
foreach ($data as $d) {
$conv = new \DateTime($d->created_at);
$d->conv = intval($conv->format('U'));
$d->diff = $d->conv - $d->unix;
}
return $data;
}
... and result is
0
id 1
created_at "2021-03-18T12:36:59.000000Z"
unix 1616067419
conv 1616071019
diff 3600
As you see, the difference is 1 hour (as my timezone offset). Where is a problem?
Thanks.

Get availability of formers for a sitting

I have two forms; the first is the form formers with two fields (name, firstname).
I also have the form trainings with two fields (date_sitting, fk_former).
My problem, if I want to add the other sitting today (07/07/2019), I would like to see only the formers who have no training today.
Here, I retrieve a former who has a sitting today.
Do you think it's possible to get only the formers who have no of sitting for now?
Edit: 10/07/2019
Controller Training
public function index()
{
$trainings = Training::oldest()->paginate(5);
$formersNoTrainingToday = Training::whereDate('date_sitting', "!=", Carbon::today())
->orWhere('date_sitting', null)->get();
return view('admin.trainings.index', compact('trainings', 'formersNoTrainingToday'))
->with('i', (request()->input('page',1) -1)*5);
}
And
public function create()
{
$formers = Former::all();
return view('admin.trainings.create', compact('formers','trainings'));
}
I would like to see only the formers who have no training today.
Sure - you can determine your correct list of candidates to show by using the following query:
$formersNoTrainingToday = Training::whereDate('date_sitting', "!=", Carbon::today())
->orWhere('date_sitting', null)->get();
This should work... but it assumes a few things within your code / db. If this fails, consider a few options to replace the whereDate section above:
Using where:
->where('date_sitting', '!=', \Carbon::today()->toDateString())
Using formatted date if that column on the DB is a different format than Carbon:
->whereDate('date_sitting', "!=", Carbon::now()->format('m/d/Y'))
If you're not using Carbon for some reason, you can try the raw query route for today:
->whereDate('date_sitting', "!=", DB::raw('CURDATE()'))
Bottom line, here are a number of ways to get close to this. But you may need to tweak this on your own to suit your needs. You may need to take Timezone or some hours of difference into account, so you may need to add a range or buffer. But the above should get you close if not all the way there.
HTH

date calculation in laravel model

I want to return values in my model based on dates but not sure how to?
Logic
calculate the date that post has published + 7 days after that and return true or false.
example
Let say I want add new label in posts from the date that post published till 7 days after that, and in the day 8th that new label be removed.
How do I do that?
Update
I ended up with something like this in my model currently
public function isNew($query){
return $query->where('created_at', '<=', Carbon::now()->toDateTimeString());
}
but it returns Undefined variable: isNew in my blade.
please give me your suggestions.
Are labels stored in a separate table from your posts? You could use 'effective dating'. Have indexed 'show_at' and 'hide_at' fields in your labels table. Have entries there get created as soon as the post does. You could use database triggers to do this, or model observers. And when querying for all labels related to a given post, make sure they're between those dates (or those dates are null).
For a more simple solution, you could do a whereRaw('CURRENT_DATE <= DATE_ADD(dateFieldName, INTERVAL 7 DAY)'). If timezones are a factor, you could use the CONVERT_TZ() function, though it's generally good practice to store everything in UTC to avoid those issues.
I would recommend you make use of Carbon:
https://carbon.nesbot.com/docs/#api-difference
That link should help a lot but to point you in the correct direction, you should be able to do a comparison:
I assume you DB date is held in ISO (Y-M-D, eg: 2019-01-07)
$date= Carbon::createFromFormat('Y-m-d', $dateFromDB);
if($date->diffInDays(Carbon::now() < 8){
Code for Add Label here
}
Or if you are using timestamps:
$date= Carbon::createFromTimestamp($dateFromDB);
if($date->diffInDays(Carbon::now() < 8){
Code for Add Label here
}
Solved
thanks for all the helps I solved my issue with code below:
public function getisNewAttribute(){
$now = Carbon::now();
return Carbon::parse($now) <= Carbon::parse($this->created_at)->addDays(7);
}

How to add minutes to to a date in laravel

There are few ways that I can do this using PHP but I could not find a way to do that using laravel specific way.
I have a time that is coming from database in below format: Y:M:s
ex: 05:15:00
This is what I want to do:
add 30 minutes to that date, according to above example result should be: 05:45:00
Below is my current code and I want to add 30min to $endTime:
//get database value according to selected date
$allocatedDateQuery = DB::table('appointments')->where('date', $request->date)->get();
//loop throug every record to get time
foreach ($allocatedDateQuery as $value) {
$time = $value->time;
$endTime = $time;
}
I just got a perfect solution from here.
Use Carbon extention to simply acheive that.
What you have to do is parse your time to Carbon object and then you can use addMinutes() to do that and then you can format() if you want:
foreach ($allocatedDateQuery as $value) {
$time = Carbon::parse($value->time);
$endTime = $time->addMinutes(30);
$allocateValidateMessage .= Carbon::parse($value->time)->format('H:i') . ' - ' . $endTime->format('H:i') . ' ';
}
Usually I use php's date, you can give this a try
Date("Y:M:s", strtotime("30 minutes", strtotime($value->time))
That is converting your time into a string, adding 30minutes to it and converting it to the date format of your desire
Since you said you are grabbing the date from the database I am assuming you are also using Eloquent to query from the database.
You can use Eloquent Mutator Method in your Database Modal Class to mutate the data like this:
public function getAppointmentsAttribute($value) {
return Date("Y:M:s", strtotime("30 minutes", strtotime($value->time)));
}
You can even add another attribute without mutating the original value using Attribute assignments as well. This method caches your query and reduces database calls. Since you do not need to run local loops on the record your code is much cleaner.

Resources