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.
Related
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();
Is there any way to put a manual function inside a query in Laravel.
I've timestamp saved in string in DB. I want to convert timestamp from one timezone to another. All the timestamp is inserted in one time zone, and depending upon my user I fetch the timestamp and convert it into their timezone.
what I want to achieve is something like this..
$query = BlogCategory::select('merchant_id', userTime(added_at))
->where('site_id', $site_id)
->get();
userTime() function takes two parameter, the timestamp and the timezone and converts the timsestamp to time of the user.
I want to use userTime() function before fetching the data. I dont want to fetch the data first and then do foreach and so on.
I know I might be absolutely absurd but is there anything of this sort in Laravel?
Well you can achieved that using collection map
$query = BlogCategory::select('merchant_id', 'added_at')
->where('site_id', $site_id)
->get();
$dateAdded = $query->map(function ($data) {
// try this if error $data['merchant_id']
return array(
'merchant_id' => $data->merchant_id,
'added_at' => $this->userTime($data->added_at)
);
})
dd($dateAdded);
Read Collection documentation here: https://laravel.com/docs/5.8/collections
You should use the selectRaw statement and let your DB do this logic for you if you don't want to loop over the result set.
For example if your underlying database is MySQL you can use the CONVERT_TIMEZONE function and do something like this.
BlogCategory::selectRaw('merchant_id, CONVERT_TZ(added_at, "GMT", "MET") as added_at')
->where('site_id', $site_id)
->get();
To get all records of the current day, I did
$dt = Carbon::now();
$dataToday = Data::whereDay('created_at', $dt->day)->get();
To get records from this week, I tried the following but without success.
$dataThisWeek = Data::where('created_at', $dt->weekOfYear);
$dataThisWeek = Data::where('created_at', $dt->weekOfMonth);
$dataThisWeek = Data::whereWeek('created_at', $dt->week);
How do we approach this with Eloquent and Carbon (preferably) or a native MYSQL function?
Try this:
Data::whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->get();
To set the week start/end:
Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);
You can also try
$dataThisWeek = Data::where(\DB::raw("WEEKOFYEAR(created_at)"), $dt->weekOfYear)->get();
For some reason using Laravel 7.4^ the accepted solution above is not working on my end. No data is shown, to fix it I added a format like this:
$now = Carbon::now();
Data::whereBetween("created_at", [
$now->startOfWeek()->format('Y-m-d'), //This will return date in format like this: 2022-01-10
$now->endOfWeek()->format('Y-m-d')
])->get();
To complete #user320487 answer:
To avoid conflict between different third-party libraries, static setters should not be used. Use $weekEndsAt optional parameter instead when using endOfWeek method.
Data::whereBetween('created_at', [Carbon::now()->startOfWeek(Carbon::SUNDAY), Carbon::now()->endOfWeek(Carbon::SATURDAY)])->get();
You can also use the 'first_day_of_week' locale setting to change the start of week according to current locale selected and implicitly the end of week.
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.
I have a model Users And every time user logges in loggedin_at field is updated.
$user = User::find(1);
$user->token = md5(time());
$user->loggedin_at = date('Y-d-m H:i:s');
$user->save();
return $user;
But I know from experience already that sometimes there is difference between MySQL time and PHP time. So when you use comparisons like time > NOW() - INTERVAL 1 HOUR it might now work correctly because you set date from PHP and compare it from MySQL.
Anyway my question is I want to use NOW() to update my date. I try
$user->loggedin_at = DB::raw('NOW()');
But that does not work. By looking into Eloquent source I've managed out this to work
$user->loggedin_at = new \Carbon\Carbon();
This is what Eloquent uses to alter times.
How to use NOW() to set time?
Should I use NOW() or better continue with Carbon?
It's better to use Carbon, it's what it's there for. Laravel uses it out of the box, and uses it within created_at and updated_at.
If you use Carbon, also, you can synchronize PHP's time and Carbon's "NOW" using the timezone configuration inside of config/app.php.
Furthermore, if you want to change the result you get from Carbon, you can do something like:
$now = Carbon::now(new DateTimeZone('Europe/London'));
//can also be passed as a string
$now = Carbon::now('Europe/London');