How to only use created_at in Laravel
Eloquent does not provide such functionality out of the box, but you can create it on your own using the creating
event callback:
class User extends Eloquent {
public $timestamps = false;
public static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->created_at = $model->freshTimestamp();
});
}
}
How to remove updated_at while keeping the created_at in Eloquent ORM Laravel
In your model add these two lines:
public $timestamps = ["created_at"]; //only want to used created_at column
const UPDATED_AT = null; //and updated by default null set
second way:
public $timestamps = false; //by default timestamp true
add function like this:
public function setCreatedAtAttribute($value) {
$this->attributes['created_at'] = \Carbon\Carbon::now();
}
for more info about laravel timestamp see
Custom created_at and use only custom created_at
I've just tested this and it works perfectly:
const UPDATED_AT = null;
const CREATED_AT = 'ct';
There's no need to do anything else. With this solution, Laravel will use ct
as created_at
and will not add updated_at
to any update queries.
How to let Laravel pivot table use only created_at?
You could take another approach:
- Skip the
withTimestamps()
method (to avoid adding bothcreated_at
andupdated_at
columns). - Add a custom pivot column:
created_at
.
So your code:
class Foo extends Model
{
public function bars() {
$this->belongsToMany(Bar::class)->withPivot('created_at');
} // ^^^^^^^^^^^^^^^^^^^^^^^^
}
Now, with this approach you will need to set the value of created_at
manually when creating records:
$foo = Foo::find(1);
$foo->bars()->attach($someId, ['created_at' => now()->format('d-m-Y H:i:s')]);
// or whatever you use as date ^^^^^^^^^^^^^
Also, this column won't be casted as a Date
by default -as opposed to what Laravel do with timestamp columns- so this:
$foo->bars()->first()->pivot->created_at
won't be an instance of Carbon. If you want it though, you could create a custom Pivot model, then specify the column to cast and update your relationship to use the custom Pivot model:
Pivot model FooBar.php
class FooBar extends Pivot // <--
{
protected $casts = [
'created_at' => 'datetime:d-m-Y H:i:s',
];
}
Then in your Foo.php
class:
class Foo extends Model
{
public function bars() {
$this->belongsToMany(Bar::class)->using(FooBar::class)->withPivot('created_at');
// ^^^^^^^^^^^^^^^^^^^^
}
}
Disable Laravel's Eloquent timestamps
You either have to declare public $timestamps = false;
in every model, or create a BaseModel, define it there, and have all your models extend it instead of eloquent. Just bare in mind pivot tables MUST have timestamps if you're using Eloquent.
Update: Note that timestamps are no longer REQUIRED in pivot tables after Laravel v3.
Update: You can also disable timestamps by removing $table->timestamps()
from your migration.
How to change format of created_at and updated_at in laravel Model?
You can use something like this:
public function getCreatedAtAttribute($date)
{
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d H:i');
}
public function getUpdatedAtAttribute($date)
{
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d H:i');
}
use these
How to disable or remove updated_At and Created_at when returning data
There are different methods you can use.
Method 1 : Fetch only required fields from the database
You can use select()
method for retrieving only required fields from db. Hence you can omit the unnecessary fields.
$placeType = PlaceType::with(['places' => function ($query) {
$query->select('id', 'name', 'description', 'icon',
'image_name', 'rating', 'longitude', 'latitude',
'availability', 'status', 'place_type_id'); //timestamps excluded
}])
->select('id', 'name', 'icon', 'status') //timestamps excluded
->where('id', 1)
->get();
return response()->json(['placeType' => $placeType]);
This code will output only specified fields both in the parent model (placetype
) and child model (places
).
If you use these customized select query more than once and writing all field names multiple time is difficult, then you could use model scope like the following.
PlaceType Model
// add all columns from your table
protected $columns = ['id', 'name', 'icon', 'status', 'created_at', 'updated_at'];
public function scopeExclude($query,$value=[])
{
return $query->select( array_diff( $this->columns,(array) $value) );
}
Place Model
// add all columns from your table
protected $columns = ['id', 'name', 'description', 'icon', 'image_name',
'rating', 'longitude', 'latitude', 'availability',
'status', 'place_type_id', 'created_at', 'updated_at'
];
public function scopeExclude($query,$value=[])
{
return $query->select( array_diff( $this->columns,(array) $value) );
}
Then you could remove unwanted fields like the following
$placeType = PlaceType::with(['places' => function ($query) {
$query->exclude(['created_at', 'updated_at']); //exclude fields from Place model
}])
->exclude(['created_at', 'updated_at']) //exclude fields from PlaceType model
->where('id', 1)
->get();
Courtesy : This SO answer by @Razor
Method 2 : Hide your column from serialization where you need
You can hide your column from serialization using laravel's makeHidden()
method. In this method after fetching rows with all fields, you are making the specified fields as hidden. [Please note that the excluded variables won't appear on json
but may visible on dump].
//get rows with all fileds (except hidden)
$placeType = PlaceType::with('places')->where('id', 1)->get();
//making timestamps hidden in child model's rows
$placeType->places->makeHidden(['created_at','updated_at']);
//making timestamps hidden in parent model's rows
$placeType->makeHidden(['created_at','updated_at']);
return response()->json($placeType);
Courtesy : This SO answer by @sajed
Method 3 : Using Hidden property
If the timestamps are unnecessary in most of the time in the app, you could use the model's hidden
property.
PlaceType Model & Place Model
protected $hidden = ['created_at', 'updated_at'];
Hope this will be helpful. /p>
How to change default format at created_at and updated_at value laravel
In your Post
model add two accessor methods like this:
public function getCreatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
Now every time you use these properties from your model to show a date these will be presented differently, just the date without the time, for example:
$post = Post::find(1);
echo $post->created_at; // only Y-m-d formatted date will be displayed
So you don't need to change the original type in the database. to change the type
in your database you need to change it to Date
from Timestamp
and you need to do it from your migration (If your using at all) or directly into your database if you are not using migration. The timestamps()
method adds these fields (using Migration) and to change these fields during the migration you need to remove the timestamps()
method and use date()
instead, for example:
$table->date('created_at');
$table->date('updated_at');
How to disable updated_at and created_at when saving data in Laravel
Just add this:
public $timestamps = false;
In your model and you are good to go.
Related Topics
Php: Possible to Automatically Get All Posted Data and Multiple Checkbox Unchecked
How to Block Uploads of Nude Images
How to Convert the Time from Am/Pm to 24 Hour Format in PHP
Convert Epoch Time to Date PHP
Problems with Lib-Icu Dependency When Installing Symfony 2.3.X via Composer
Working with Two Entity Managers in the Same Bundle in Symfony2
Recommended Server for Continuous Integration for a PHP Project
Place PHP Results Inside HTML Page
How to Run Yii2 Application on Hosting
Check If String Is Just White Space
Symfony2 - How to Switch from "Dev" to "Prod"
How to Return JSON Data from PHP Mongocursor
How Is Annotation Useful in PHP