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', ' ')}}
Related
I have 3 databases like theses :
formations subjects formation_subject
| id | name| | id | name | is_optional | | formation_id | subject_id |
___________ _________________________ ____________________________
where in the Models\Subject,
public function formations()
{
return $this->belongsToMany(Formation::class);
}
and in the Models\Formation,
public function formationsSubjects()
{
return $this->belongsToMany(Subject::class);
}
in my controller, I have :
$formations = Formation::get()->pluck('name','id);
$options = Subject::where('is_optional', 1)->get();
On my blade, I have a dropdown of $formations,
and whenever the selected option of that dropdown is changed,
I'd like to get a list of dropdown of $options,
which are the Subject are optional ('is_optional' == 1) and the Subject belongsTo(Many) the previously selected $formations
I've tried like this,
$options = Subject::where('is_optional',1)->whereIn('id', function($query) use ($formations){
$query->select('formation_id')
->from('formation_subject')->whereIn('formation_id',$formations);
})->get()->pluck('code', 'id');
But the results didn't matched with what's supposed to appear, and stay the same no matter the formations dropdown is selected.
Laravel has a very thorough documentation I suggest that you study the basics of Laravel and/or reading the documentation: https://laravel.com/docs/9.x
To answer your question, you can use the eloquent whereHas method: https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
And I think this is the code that want:
$formationIds = Formation::whereHas('formationsSubjects', function (Builder $query) {
$query->where('is_optional', 1);
})->get()->pluck('id');
Laravel is on the backend, and whatever is in Blade file is just HTML that is send to the client (front-end)
If you want to do something in one field and the DATA get changed, to must get that data from the backend, either from an AJAX request, or re-render the whole page. AJAX request is of course prefered
You can write Javascript to do AJAX request yourself, or you may want something automatic, look for livewire
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;
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 = [];
Im building the chat section of my app with vueJs and laravel backend. I want to fetch my messages grouped by days. So when messages display, I want them to look something like this.
`Today
**All messages sent and received today, ordered by time**
Yesterday
**Yesterday's messages**
9/12/2018
**Messages for that day**
In my Chat model, I wrote an accessor for this like so;
public function getMessagesAttribute(){
return $this
->groupBy(function($q){
return $q->created_at->format('Y-m-d');
});
However, this does not give anything different from what I got when I use orderBy('created_at', 'ASC') in the controller. I will appreciate any assistance/guidance to achieve what I want please.
You could feed the results of your function into a loop that starts with the first date, sets the date as a variable, then compares it to the next date, which, if the next date has a smaller value, it gets preceded with a header field to result in grouping.
$date=null;
$next_date=null;
while($this) {
$date = $this->created_at;
if($next_date != null && $next_date<$date) {
*put your group title here*;
*put date/message here*;
} else {
*put date/message here*;
}
$next_date=$date;
}
Maybe build an array out of it, or something like that.
What about
$today = \Carbon\Carbon::now()->format('Y-m-d');
$yesterday = \Carbon\Carbon::yesterday()->format('Y-m-d');
$any_day = \Carbon\Carbon::createFromFormat('d/m/Y', '9/12/2018')->format('Y-m-d'); //used your example date
$messages_today = Message::where('created_at', 'like', "{$today}%")->orderBy('created_at', 'desc')->get();
$messages_yesterday = Message::where('created_at', 'like', "{$yesterday}%")->orderBy('created_at', 'desc')->get();
$messages_any_day = Message::where('created_at', 'like', "{$any_day}%")->orderBy('created_at', 'desc')->get();
It needs some tweeking according to your needs. But that should do the trick for you.
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' ];