I have a field in my database called "deadline" which is of DATE format, and I want to use Eloquent to say that if the deadline field does not match Carbon::now(); but isn't in the future then don't show this row.
How can I achieve this?
Select records where deadline is greater than or equal to today's date() in the Y-m-d format.
Model::where('deadline','>=', date('Y-m-d'))->get();
Laravel works with Carbon for formatting timestamps etc, which you can easily set the deadline column as one of those Carbon objects with a Laravel date mutator allowing you formatting abilities.
But for a select statement, i'd just use the above personally.
Related
On my project, I created an option for the user to search by date, but in my database, all the inserts are in DateTime format (yyyy-mm-dd h:m:s), while the search is made only with a simple date(yyyy-mm-dd) input.
Is there any way I can compare these two values, so the user can find all the inserts on the given date?
you can use eloquent whereDate with format Y-m-d
YourModel::whereDate('created_at','2021-11-24')->get();
or without model
DB::table('your_table')->whereDate('created_at','2021-11-24')->get();
I have a table in the database where the records contain a start_date and an end_date. An example of the data format is:
"13/03/2020"
How can I fetch all records for the week? I have tried the code below. However, it does not return any data.
$date = Carbon::now()->format('d/m/Y');
$dateInWeek = Carbon::now()->addDays(7)->format('d/m/Y');
$holidays = Holiday::where('start_date', '>=', $date)
->where('end_date', '<=', $dateInWeek)->get();
Probably correct solution is to change string to datetime in db, if it is not an opinion then you can create custom function in database that will handle strings in way you want.
You shouldn't use string when you can use date / datetime column type.
But that being said - it's not always up-to us to be able to change DB structure.
Solution 1
Depending on what SQL you are using there is usually function to cast string to date.
For example MySQL: STR_TO_DATE(string, format)
https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_str-to-date
Solution 2
You can make array containing all dates of week using Carbon.
then in query: ->whereIn('start_date', $datesArray)->whereIn('end_date', $datesArray)
I'd still suggest changing column type to date if possible
I'm trying to make an investment website where I want to set an expiration date exactly after a year that the registration was made. Upon the registration, an initial deposit is required which is the one with the value "500" which is fixed on every registration. I want to use the created_at timestamp from my database table money_trade_deposits as the reference for the start date and calculate the expiration date based on that after a year and pass it on my laravel blade view. I'm new to laravel and I have no idea how to this.
This is my money_trade_deposits table and I wanna base the expiration date from the created_at date.
Or it it possible to add a new timestamp row which will automatically calculate the expiration date adter a year? Any help will be much appreciated. Thanks a lot!
Since the created_at is automatically casted as a Carbon instance in Laravel, you can calculate the expiration date one year after with the ->addYear() method.
Ex: $model->created_at->addYear()->toDateTimeString().
Reference: Carbon doc
You must use Carbon here to add a year from the day of the initial deposit.
Laravel automatically wraps up created_at to Carbon instance, and Carbon instance you can easily add year using addYear() function. See Documentation https://carbon.nesbot.com/docs.
I will suggest you to create a new column for expiration date and set it initially rather than adding a year to created_at each time to check expiration. Anyway, Carbon is very useful for this type of date processings.
I am writing a program that sends emails to users when their subscription is about to expire so i have a table in my database with a date stored in varchar as 12th April 2018 I am using that format because it is easy to read therefore I don't have to convert it again later.. But when i write
$currentdate= Carbon::now()->toDateTimeString();
$threeDaystoExpire =Carbon::now()->addDays(130)->toDateTimeString();
return $expiredPacks = DB::table('subscriptions')
->whereDate('expires_on','>',$currentdate)
->whereDate('expires_on','<=',$threeDaystoExpire)
->get();
I get a blank return output but when i change expires_on to created_at that is formatted like this 2018-04-12 12:41:36 I get the correct output. I tried changing the format of $currentdate and $threeDaystoExpireto match the data in my database as advised by previous threads i read and tried again like this
$currentdate= Date('dS F Y', strtotime(Carbon::now()->toDateTimeString()));
$threeDaystoExpire =Date('dS F Y', strtotime(Carbon::now()->addDays(130)->toDateTimeString()));
return $expiredPacks = DB::table('subscriptions')
->whereDate('expires_on','>',$currentdate)
->whereDate('expires_on','<=',$threeDaystoExpire)
->get();
I get the same empty output. I am currently stuck. All the posts I've read only uses one value so they just make a statement to return just the date, convert it to a timestamp format then compare. I have hundreds of those date and I cant write a statement for each one so any help to tackle this problem will be greatly appreciated.
The toDateTimeString() method converts the Carbon DateTime object into a specific format such as 1975-12-25 14:15:16 which simply isn't a match for your varchar field.
Try using the Carbon API to convert Now to the format you need...
$currentdate = Carbon::now()->format('dS F Y');
$threeDaystoExpire = Carbon::now()->addDays(130)->format('dS F Y');
I'll also point out that the comparison will look at the day first, then the string value of the month, then the numerical year. This will give you very odd results. I might recommend strtotime on the output of your varchar field and use that instead instead of the other way around.
Do yourself a favor and store dates as YYYY-MM-DD (in a date column), it will make your life much easier. It's also easy to read and has been the standard format for ages (for good reasons).
The format you choose for your frontend is a different matter. You can maybe use an accessor for that.
I made a separate field to store the date in a human readable format so I don't have to convert it later in my app, then stored the timestamp format of the same date in a separate field to handle the calculations. It is way easier to use, read and saves me the stress of converting from timestamp then later reconverting back to timestamp which doesn't make sense.
As advised here to leverage platform tools more. I decided that data that will be used in different forms will be stored in a general format and i will allow the platform handle how they want to represent those data.
I am using this code successfully, but is there a way to run this where I don't need to convert my variable from a string to a number?
I am confused and wondering if I am doing it efficiently because the mysql timestamp datatype is a string but the php timestamp is a number. There should be a date format conversion for the mysql timestamp,no?
date(DATE_ATOM, strtotime($program->start_time))
the date function takes a timestamp long datatype but mysql stores timestamps in a datetime string format. Is there another way to do this where I just convert once?
I don't know why do you need to change the dates in your code.
In Laravel base Model, dates works as Carbon objects. When that fields are stored in database, they're mutated to database date format. That's because date fields have their owns getter/setters in base model.
You don't need to change your custom date fields formats, only declare them in the $dates Model propertie so it can mutate that fields when they are stored in database.
For example, in this User model class the attribute start_time will be mutated from Carbon to MySQL format when it will be saved.
Class User extends Eloquent
{
protected $dates = ['start_time'];
}
You can read more about that here http://laravel.com/docs/4.2/eloquent#date-mutators
I expect that would help you to understand it better.