How do I convert date and time to timestamp in Laravel 8? - laravel

I am using Laravel 8 and Jdf and I want to convert the date and time to timestamp, but it is always 0, I do not know why.
I want the start date and end date to be timestamped
file AdminController.php
public function add_incredible_offers(Request $request)
{
$date1=$request->get('date1');
$date2=$request->get('date2');
$offers_first_time=getTimestamp($date1,'first');
$offers_last_time=getTimestamp($date2,'last');
return $offers_first_time;
}
file helpers.php
See the image here file helpers.php

You're sending parameters to the function in wrong order.
change
$offers_first_time=getTimestamp($date1,'first');
$offers_last_time=getTimestamp($date2,'last');
to
$offers_first_time=getTimestamp('first',$date1);
$offers_last_time=getTimestamp('last',$date2);
alternatively you can easily use Carbon.
$offers_first_time = \Carbon\Carbon::make($request->input('date1'))->timestamp;
$offers_last_time = \Carbon\Carbon::make($request->input('date1'))->timestamp;

Related

Why is created_at converted to Zulu format in Interia.js?

I am using Laravel 8 together with Interia.js.
I have a simple route like this:
Route::get('/test', function () {
$user = User::first();
return Inertia::render('Test', compact('user'));
});
If I dump the user in controller I see that the attribute created_at is in format "YYYY-mm-dd H:i:s". However, at the front end the timestamp is presented in Zulu format. Why? And how can I prevent this conversion?
Currently I have to reformat like this at the front-end:
{{ new Date(user.create_at).toISOString().slice(0, 19).replace('T', ' ')}}

Laravel Orchid - unable to retrieve values from URL

I have an Orchid screen for displaying reports and want to display by month and year.
http://url.com/main/report/2022/01
I have this in my platform routes
Route::screen('/main/report/{year}/{month}', DashboardReportScreen::class)
->name('platform.report');
How can I access year and month from within my screen file?
Inside my DashboardReportScreen, the query function looks like this:
public function query(): iterable
{
print_r($year);
// NULL RETURN
}
How can I access custom parameters in my URI from within my screen?
You need to pass the arguments to the "query" function in your screen file as it is here https://orchid.software/en/docs/quickstart-crud/

How to set a global Carbon format in Laravel 7

I've just upgraded my Laravel application from 6.x to 7.x and I'm having problems with dates/timestamps. I know some things changed in regards to that.
I'm trying to set a default Carbon format globally. I've got a few custom timestamp fields in my database, created like so:
$table->timestamp('published_at')->nullable();
And I started getting following errors after upgrade, whenever these fields are updated:
Invalid datetime format: 1292 Incorrect datetime value: '2020-04-04T11:00:00.000Z' for column 'published_at'
I tried to use the suggested method on each model:
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
But this method never gets called, and it doesn't work.
However, setting up a mutator works fine:
public function setPublishedAtAttribute($value)
{
$this->attributes['published_at'] = Carbon::parse($value)->format('Y-m-d H:i:s');
}
But I was trying to avoid the repeated code for these fields. In total, there are about 14 fields where I'd need to create these mutators, so I was wondering if there is a better way?
Ok I figured it out. I just had to add these timestamps to
protected $dates = [];

Display Tutorials Based On Tutorial Date and Specified Timezone in Laravel

Please help. I'm working on a site that debut at specific date and time. Tutorials are being displayed to every students on date set on each tutorials. However, I want the tutorials to debut not just by the date and time set on each tutorials but also based on the timezone set on each tutorial. For example, if a tutorial is set to debut today at 8:00pm Eastern Standard Time (EST) of the United States, it should debut at that time instead of debuting at the application set timezone.
I wrote the below code using Laravel collection filter() which seems to do the trick. However, the page is taking longer to load and I'm unable to use laravel paginate(). I need to use Laravel paginate() to reduce the number of records being pulled at once. There are over four thousand tutorials. Please help.
// upcoming tutorials
$tutorials = Tutorial::orderBy('id', 'desc)->paginate(20);
$futureTuts = $tutorials->filter(function ($value, $key) {
$today = new \DateTime('now');
$show_date = new \DateTime($value->show_date, new \DateTimeZone($value->timezones->name));
return $show_date > $today;
});
$upcoming_tuts = $futureTuts->all();
Please any solutions around this to be able to use Laravel default paginate(). I believe using Laravel pagination will cause the page to load faster. I'm using Laravel 5.4.
Thanks
try to use datatable can filter your data from database as api
here is package
yajra/laravel-datatables-oracle
and if you want to use as published try something different like this
add a column as published_at
$table->dateTime('published_at');
than in your model define your table
protected $dates = ['published_at'];
public function setPublishedAtAttribute($date){
$this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d', $date);
}
public function scopePublished($query)
{
$query->where('published_at', '<=', Carbon::now());
}
public function scopeUnpublished($query)
{
$query->where('published_at', '>', Carbon::now());
}
public function getCreatedAtAttribute($date)
{
return $this->asDateTime($date)->toFormattedDateString();
}
now you can use published scope in your controller like this
$tutorials = Tutorial::orderBy('created_at', 'desc')->published()->paginate(5);

Laravel "Unexpected data found" error when trying to change format of Carbon created_at date

When I try to modify the format of the default created_at field of my Resource model, I get the following error:
{
"error":{
"type":"InvalidArgumentException",
"message":"Unexpected data found.
Unexpected data found.
The separation symbol could not be found
Unexpected data found.
A two digit second could not be found",
"file":"\/var\/www\/html\...vendor\/nesbot\/carbon\/src\/Carbon\/Carbon.php",
"line":359
}
}
Here is the code that produced the above error:
$tile = Resource::with('comments, ratings')->where('resources.id', '=', 1)->first();
$created_at = $tile->created_at;
$tile->created_at = $created_at->copy()->tz(Auth::user()->timezone)->format('F j, Y # g:i A');
If I remove ->format('F j, Y # g:i A') from the above code, it works fine, but it's not in the format I want. What could the problem be? I have almost identical code elsewhere in my app and it works without error.
UPDATE:
Using setToStringFormat('F j, Y # g:i A') does not cause an error, but returns null.
Adding the following code to my model worked for me:
public function getCreatedAtAttribute($date)
{
if(Auth::check())
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->copy()->tz(Auth::user()->timezone)->format('F j, Y # g:i A');
else
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->copy()->tz('America/Toronto')->format('F j, Y # g:i A');
}
public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('F j, Y # g:i A');
}
This allows me to use created_at and updated_at in the format I want.
I did experience the same problem, and in my search for an answer I stumled across How do you explain the result for a new \DateTime('0000-00-00 00:00:00')? .
I decided to change the datetime-columns in the database to nullable with default value = NULL, to prevent fields from having value '0000-00-00 00:00:00'.
My migration in laravel 5 looks like this:
Schema::table('table', function($table)
{
$table->dateTime('created_at')->nullable()->default(null)->change();
$table->dateTime('updated_at')->nullable()->default(null)->change();
});
It's not a carbon issue, it's a conflict between a setAttribute or getAttribute in your model.
You shouldn't try to change the format of created_at. It has to be a Carbon object. If you want to display the created_at date in a different format, then just format it at the time you output it. Or you may want to create a method that changes the format so you can call it whenever you want it in a different format. For example, add a method like this to your Resource class:
public function createdAtInMyFormat()
{
return $this->created_at->format('F j, Y # g:i A');
}
You can also have that function adjust the timezone, etc. Then you can use $tile->createdAtInMyFormat() for example to get your special format created_at from your $tile object.
You needed to parse given date before saving
user this code
Carbon::parse($request->input('some_date'));
first add this to your model:
protected $casts = [
'start_time' => 'time:h:i A',
'end_time' => 'time:h:i A',
];
and then you can further format it with either Carbon or other Php native functions, such as
date('h:i A', strtotime($class_time->start_time)) // "09:00 AM"
I ran into this issue, and it was simply a matter of uses dashes instead of slashes.
$model->update(['some_date' => '2020/1/1']); // bad
$model->update(['some_date' => '2020-1-1']); // good
Reminder: If you specify your dates on your model, Eloquent is smart enough to convert it for you.
protected $dates = [ 'some_date' ];

Resources