0
votes

I'm using Laravel 8 and in my application, I have Belongs to Many relations with a custom model, and I want to remove the 'updated_at' field.

Relation

public function tracks() 
{
    return $this->belongsToMany(Track::class)
        ->using(CollectionTrack::class)
        ->withPivot('sort'  , 'created_at' , 'id');
}

Custom model

class CollectionTrack extends Pivot
{
    use Sortable;

    public const UPDATED_AT = null;
    public $incrementing = true;
    
    public static function enableAutoSort () {
        return false;
    }
}

The issue is that when I want to sync, it tries to fill the updated_at field.

Column not found: 1054 Unknown column 'updated_at' in 'field list'

However, I removed the updated_at from the Model using the following line.

public const UPDATED_AT = null;

And also, only get the created_at in withPivot.

When I remove the created_at from withPivot, the issue goes away, but in that case, when I retrieve the data created_at won't be in the fields.

Note: my goal is to disable the updated_at timestamp and only have created_at so when I attach a new record, the created_at set and when I retrieve it, the model has these pivot fields 'sort', 'created_at', 'id.'

3
Just try to change the updated_at field to nullable bro - daffaquraisy
Did you have tried this answer? It should work for you stackoverflow.com/questions/29886497/… - Rob

3 Answers

3
votes

I think you can remove $table->timestamps() from your migration and just add a field created_at having default value current time stamp.

$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));

should work I guess.

There is another answer you can refer.

0
votes

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
votes

ORIGINAL ANSWER: https://stackoverflow.com/a/59171175/14290461

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 false

add function like this:

public function setCreatedAtAttribute($value) { 
    $this->attributes['created_at'] = \Carbon\Carbon::now(); 
}

for more info about laravel timestamp see