Disable Laravel's Eloquent timestamps

后端 未结 10 1443
余生分开走
余生分开走 2020-12-04 08:54

I\'m in the process of converting one of our web applications from CodeIgniter to Laravel. However at this moment we don\'t want to add the updated_at / c

相关标签:
10条回答
  • 2020-12-04 09:29

    Simply place this line in your Model:

    public $timestamps = false;

    And that's it!


    Example:

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Post extends Model
    {
        public $timestamps = false;
    
        //
    }
    

    To disable timestamps for one operation (e.g. in a controller):

    $post->content = 'Your content'; 
    $post->timestamps = false; // Will not modify the timestamps on save
    $post->save();
    

    To disable timestamps for all of your Models, create a new BaseModel file:

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class BaseModel extends Model
    {
        public $timestamps = false;
    
        //
    }
    

    Then extend each one of your Models with the BaseModel, like so:

    <?php
    
    namespace App;
    
    class Post extends BaseModel
    {
        //
    }
    
    0 讨论(0)
  • 2020-12-04 09:29

    You can temporarily disable timestamps

    $timestamps = $user->timestamps;
    $user->timestamps=false;   // avoid view updating the timestamp
    
    $user->last_logged_in_at = now();
    $user->save();
    
    $user->timestamps=$timestamps;   // restore timestamps
    
    0 讨论(0)
  • 2020-12-04 09:31

    If you are using 5.5.x:

    const UPDATED_AT = null;
    

    And for 'created_at' field, you can use:

    const CREATED_AT = null;
    

    Make sure you are on the newest version. (This was broken in Laravel 5.5.0 and fixed again in 5.5.5).

    0 讨论(0)
  • 2020-12-04 09:31

    Add this line into your model:

    Overwrite existing variable $timestamps true to false

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    
    public $timestamps = false;
    
    0 讨论(0)
  • 2020-12-04 09:32

    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.

    0 讨论(0)
  • 2020-12-04 09:32

    just declare the public timestamps variable in your Model to false and everything will work great.

    public $timestamps = false;

    0 讨论(0)
提交回复
热议问题