I have a created_at column in my user model that I would like to format differently when accessing it in my blade template, so it is more readable. It seems like the best way to go about this is to use a cast.
I created a cast like so:
protected $casts = [
'email_verified_at' => 'datetime',
'created_at' => 'm-d-y',
];
... in my controller, I am getting a User and then doing:
dd($member->toArray());
Now, when getting a user record and doing $user->toArray() the created_at column is still in the original uncasted format, it seems the cast isn't being used at all, any idea why this is?
You can define a format for date columns using following snippet(in model):
protected $dateFormat = 'm-d-Y';
In case of updating individual timestamp fields use the following.
protected $casts = [
'created_at' => 'date:m-d-Y',
// 'updated_at' => 'datetime:Y-m-d H:00',
];
Related
I want all the dates from the server to be sent in the ISO 8601 standard in Laravel. Laravel version is 9. The created_at and updated_at columns are sent in the wanted format but my custom column is not in that format.
Here is the code of the Seeder
"questions_updated_at" => Carbon::now()->format('Y-m-d H:i:s'),
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
"updated_at" => Carbon::now()->format('Y-m-d H:i:s')
Also tested with now()
In MySQL their values are same. Migration
$table->timestamp("questions_updated_at");
$table->timestamps();
In the Model. protected $dateFormat = \DateTime::ISO8601;
In Controller return response(MyClass::where('show_on_front', true)->get());
And in Postman getting it like this.
[{
"questions_updated_at": "2022-11-16 15:02:44",
"created_at": "2022-11-16T15:02:44.000000Z",
"updated_at": "2022-11-16T15:02:44.000000Z"
}]
In app.php the time zone is 'timezone' => 'UTC'
Help will be appreciated.
You have to use casts in order to change the type of the data fetched from the data,
in the model file
protected $casts = [
'questions_updated_at' => 'datetime',
];
the timestamp is stored as timestamp and it is fetched as string from database , casts is used to change it to the prefered DateTime format , the created_at and updated_at are already casted in HasAtttributes trait
I want to transform my database entry creation inside NewsletterController.php:
$email = $request->input('email');
$table = DB::table('newsletters');
$table->insert(array('email' => $email, 'created_at' => now()));
to prevent duplicate entries. I tried doing this:
$table = DB::updateOrCreate('newsletters');
but this method does not seem to exist for DB. How would I do that?
when you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used. The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs indicating the columns to be updated.
The updateOrInsert method will attempt to locate a matching database record using the first argument's column and value pairs. If the record exists, it will be updated with the values in the second argument. If the record can not be found, a new record will be inserted with the merged attributes of both arguments
DB::updateOrInsert(['email'=>$eamil],['created_at'=>Carbon::now()]);
now, if email exists, the 'created_at' will be updated, otherwise a new row will be inserted with values of the merged array arguments
updateOrCreate you use for Eloquent Builder and updateOrInsert you use for Query Builder. Try with updateOrInsert.
$table = DB::updateOrInsert->table('newsletters')->([ 'id' => $request->id ], [
'email' => $email,
]);
Thanks to Moussab Kbeisy's comment I can validate for uniqueness which will return a 422 error if not met instead of inserting into the database:
$this->validate($request, [
'email' => 'required | unique:newsletters'
]);
$email = $request->input('email');
$table = DB::table('newsletters');
$table->insert(['email' => $email, 'created_at' => now()]);
i am trying to pass some values into a single column in laravel database table.
The values are like this 20,45,67,89
but i want them to enter into the colume like this
===USER_ID====
20
45
67
89
I have tried like below, but not working..any suggestions ?
foreach ($request->val2 as $value){
$str_explode = explode(",",$value);
DB::table('retirement')->insertGetId([
'user_id' => $str_explode,
'amount' => $request->val1,
'week' => $request->week
]);
}
Hope this will work
foreach ($request->val2 as $value){
$str_explode = explode(",",$value);
$insert = [];
foreach($str_explode as $str){
$insert[] = [
'user_id' => $str,
'amount' => $request->val1,
'week' => $request->week
];
}
DB::table('retirement')->insert($insert);
I'm not sure i understood your question clearly, i'm assuming you want to insert array to a column:
did you try to set the column in migration to Json?
did you set the $casts in the model to json or array?
protected $casts = [ 'user_id' => 'array' ];
then when you do this, you can have an array added to that column like
Posts::create(['user_id'=>[1,2,3,4]]);
normally the user_id field is set to unsignedBigInt(), that type will not accept anything but integers, you gotta check the migration column type first.
explode() is returning an array, not a single value, that's why it will fail. Instead, you should loop through all values like this:
foreach ($request->val2 as $value){
$str_explode = explode(",",$value);
foreach($str_explode as $str){
DB::table('retirement')->insertGetId([
'user_id' => $str,
'amount' => $request->val1,
'week' => $request->week
]);
}
}
As a side advice, as you are not saving the id returned by insertGetID, you can simply use insert. Moreover, it's usually a good practice to use create because this way you will also save timestamps for created and updated.
Now field updated_at is as datetime(3), so it invokes an error:
errors: "Trailing data"
Because Laravel expects timestamp type instead datetime. How to say Laravel that it is datetime field?
Log file is:
[2019-06-02 14:41:07] local.ERROR: Trailing data {"userId":8,"exception":"[object] (InvalidArgumentException(code: 0): Trailing data atCarbon\\Traits\\Creator.php:537)
[stacktrace]
esbot\\carbon\\src\\Carbon\\Traits\\Creator.php(559): Carbon\\Carbon::rawCreateFromFormat('Y-m-d H:i:s', '2019-06-07 00:0...', NULL)
I tried this:
const UPDATED_AT = "AT_lastupdateuser";
protected $casts = [
'AT_lastupdateuser' => 'datetime',
];
You can cast an attribute to your model by adding a specific key/value to the $cast array of your model. See here for more details: https://laravel.com/docs/5.8/eloquent-mutators#attribute-casting
In your case you should add the following array to your model:
protected $casts = [
'updated_at' => 'datetime',
];
Can't figure out why JSON field is being ignored.
This one doesn't work:
Registries::create([
'nr' => $old_document->no,
'metas->name' => 'r01',
]);
In model I have set:
protected $casts = [
'metas' => 'array',
];
And:
protected $fillable = [
'nr',
'metas'
];
I think the problem is in attributes casting, because this one is working:
Registries::create([
'nr' => $old_document->no,
'metas' => json_encode(['name'=>'r01']),
]);
I'm not getting any errors just JSON column stays empty.
I'm not fan of attribute casting in relational dabatases.
So it's just my guess based on documentation about array.
The array cast type is particularly useful when working with columns that are stored as serialized JSON.
You're trying to put associative array which for JSON is an object.
I might guess that it's a bug.
So try to typecast it on insert:
Registries::create([
'nr' => $old_document->no,
'metas' => (object)['name'=>'r01'],
]);
attribute casting
and make it object:
protected $casts = [
'metas' => 'object',
];
So it seams that $metas->name is working only for updating, in my case I need to insert like this:
Registries::create([
'nr' => $old_document->no,
'metas' => ['name'=>'r01']
]);