How to convert data datetime from database? - php

i have data I get from database, it’s like this:
I want to convert it to datetime because it cannot be comparing to other variabel with time value, and it cannot because there a character and other object follow there.
This is error:
How to get just its datetime and don’t make it the other object follow on value ?

Use casting on your model. In this way laravel automaticlly convert attribute to expected type if it is possible.
// Your model class
class Booking {
protected $casts = [
'batasbayer' => 'datetime'
];
}
You may find other casts here.

Take value as $items[0]->batasbayar or if its in loop : foreach($items as $item){ $item->batasbayer }. And try converting $item->batasbayer

When you want a Model field to be retrieve as a Carbon instance you can add it to the protected $dates property of That Model
This is deprecated in Laravel 8
The recommended way is to pass that field name in the $casts property and specify the type in which you want to cast that field.
protected $casts = [
'batasbayer' => 'datetime'
];

Related

i want to convert my laravel select query with update query

This is my query:
$data = Collections::select(DB:raw("REGEXP_REPLACE(tour_id,'(,2|2,|2)','') as `new_tour_id"))->get();
I want to convert this query to update all my records in the database.
This is my database table shows:
I want this result:
Since Laravel 5.x allows attribute casting so it's possible to cast attributes to another data type for converting on runtime.
In this case, just declare a protected $casts property for example:
protected $casts = [
'tour_id' => 'array', // Will converted to (Array)
];
then store your ids like this
and finally search like this :
->whereJsonContains('tour_id', 3)->update([...]);
read more :
JSON Where Clauses
Assuming that you have a model for this table as Tour what you have to do is this:
$tours = Tour::select('tour_id')
foreach($tours as $tour) {
$tour->update([
tour_id = $whatever_id_to_update
]);
}

how do you parse this date in PHP

I want to ask if how do you parse this date to look like : "12/24/1990" using Carbon in laravel or built in php date methods
$user->profile->birthdate
Just do this
use Carbon\Carbon;
Carbon::parse($user->profile->birthdate)->format('m/d/Y')
You may use date mutators like this in your Profile model (or date casting as #Jesper said):
class Profile extends Model
{
protected $dates = [
'birthdate', // date fields that should be Carbon instance
];
}
So, whenever you retrieve the model, Laravel will automatically cast the birthdate property to Carbon instance and you can use the format method to format it, for example:
$user->profile->birthdate->format('m/d/y');
Both solutions works for both Laravel 5.* and 6.*
First Solution
You can cast your birthdate variable to always be in the format you want, by putting the following in your Profile model.
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'birthdate' => 'datetime:m/d/Y',
];
Reference:
https://laravel.com/docs/6.x/eloquent-mutators#date-casting
Second solution:
You can also cast the birthdate to always be a Carbon object in your Profile model, which you can then later format as you want, using the following code:
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = [
'birthdate',
];
And then you can always do the following to format it in different ways:
$user->profile->birthdate->format('m/d/Y')
Reference: https://laravel.com/docs/6.x/eloquent-mutators#date-mutators
Using laravel Carbon, you can parse date like below
$carbonToday = Carbon::now();
$date = $carbonToday->format('m/d/Y');
Using PHP method
$carbonToday = Carbon::now();
$date = date('m/d/Y',strtotime($carbonToday));
Hope this will help you.
using Laravel carbon method
$date = "12-24-1990";
$carbon_date = Carbon\Carbon::createFromFormat('m/d/Y', $date);
using PHP method
$newdate = date('m/d/Y',strtotime($date));

Laravel blade does not respect date cast formatting

I have a birth date field in users table
$table->date('dob');
User model has Casts
protected $casts = [
'dob' => 'date:d-m-Y'
];
In Blade,
{{$user->dob}}
I was expecting 26-11-2019
but found it shows 2019-11-26 00:00:00
Why I need to format the date again in blade when display?
What did I miss?
Or what I was expecting, is not the purpose of formatting?
protected $casts = [...] tells Laravel to treat the properties as Carbon instances, but you still need to format them:
{{ $user->dob->format('d-m-Y') }}
As far as I'm aware, there isn't a way to output a default format, unless you use an accessor:
In your User.php model:
public function getDobFormattedAttribute(){
return $this->dob->format('y-m-D');
}
Then in your view:
{{ $user->dob_formatted }}
Date casting uses only for arrays or JSON, as explained here:
https://laravel.com/docs/6.x/eloquent-mutators#date-casting
You can try to do it via mutator:
https://laravel.com/docs/6.x/eloquent-mutators#date-mutators
protected $dates = [
'dob', // it will be 'Y-m-d H:i:s'
];
protected $dateFormat = 'd-m-Y'; // but you can redefine it
that will only work when you use a ->toArray() or ->toJson() on the object or collection in question, from the doc here https://laravel.com/docs/6.x/eloquent-mutators#date-casting
A way around that of you weren't using any of the above function call is to create an accessor or getter method in the model.
use Carbon\Carbon; // import the Carbon lib.
protected $dates = ['dob'];
public function getDobAttribute($value)
{
return Carbon::createFromFormat('d-m-Y', $value);
}

How can I make laravel casting array on the model?

I try like this
Data type of votes_detail in database is json
My model like this :
<?php
class Store extends Model{
protected $fillable = [ ...,'votes_detail',...];
protected $casts = [
'votes_detail' => 'array',
];
}
My controller like this :
$store = Store::find($id)
$votes_detail = $store->votes_detail;
dd($votes_detail);
The result of dd($votes_detail) is :
{"1": "1", "5": "2"}
Why the result is still json?
The result should be an array
Whereas I've set the array in cast model
How can I solve this problem?
You could use Laravel accessors. In you model define a method called exactly getVotesDetailAttribute($details):
public function getVotesDetailAttribute($details)
{
return json_decode($details, true);
}
then when you will call $store->votes_detail you will get the expected result.
After that you can use mutators to convert an array back to JSON when it is saved back in the DB. Define the method setVotesDetailAttribute($value) as follows:
public function setVotesDetailsAttribute($value)
{
$this->attributes['votes_detail'] = json_encode($value);
}
You can easily do it by converting your data to the array by using toArray() function. So it should be like
$store = Store::find($id)->toArray();
//$store contain a array.
$votes_detail = $store['votes_detail'];
make it dd($votes_detail) and get your desire result.
I think you are storing array data after json_encode() to a column which is not defined as json() in the migration like:
$table->text('votes_detail');
or
$table->integer('votes_detail');
And seems you have defined votes_detail as string, number or something else.
This is the reason behind your problem. So, define column type as json in migration like:
$table->json('votes_detail');
And then refresh your migration, your casting in the model will work and you will get your desired array.

Perform action on Laravel model once it has been filled with data

So I have a model that has a json field as an attribute. When it is retrieved, I'd like to convert that field into an array so I can do some other things with it.
For example, if the json has data like this {name:bob,email:sue} in a parameter called json, when the model object is built, I'd like it to something like this:
public function setJsonAttribute($value)
{
$this->attributes['json'] = $value;
$jsonInfo = json_decode($value, true);
$this->name = $jsonInfo['email'];
$this->email = $jsonInfo['name'];
}
This is an example of an attempt I did with a mutator, but it's not optimal. Is there any way to do this kind of thing automatically once the model has been loaded with data from the database?
Laravel 5.4
Eloquent includes a feature called array casting which converts a field from JSON to an array property on retrieval and converts the array back to a JSON string on saving.
You can enable this by adding a $casts property to your Model with the field name as the key and array as the value:
protected $casts = [
'options' => 'array',
];
https://laravel.com/docs/5.4/eloquent-mutators#array-and-json-casting
If you had options as {name:bob,email:sue} in the database, you would then access them as $model->options['name'] and $model->options['email'].

Categories