Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1 eloquent::attach() method with timestamps

I seem to have a problem with timestamps - when trying to attach User to Lectures via favorites pivot table - none of the dates updates.

Here's my migration:

Schema::create('favorites', function (Blueprint $table) {

    $table->integer('lecture_id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->timestamps();

    $table->primary(['lecture_id', 'user_id']);

});

Lecture relationship:

public function favorites()
{
    return $this->belongsToMany(User::class, 'favorites');
}

User relationship:

public function favorites()
{
    return $this->belongsToMany(Lecture::class, 'favorites')
                ->withTimestamps();
}

Whenever I attach:

$event->lecture->favorites()->attach($this->user->id);

Both fields created_at and updated_at are set to 0000-00-00 00:00:00

Any idea what I might be doing wrong?

like image 465
Sebastian Sulinski Avatar asked Nov 16 '15 17:11

Sebastian Sulinski


People also ask

What is the difference between attach and sync in laravel?

The attach function only adds records to the Pivot table. The sync function replaces the current records with the new records. This is very useful for updating a model.

What does get () do in laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function. Think of it like this: when you don't exactly know what a query will return then you need to use get() .

How do I get rid of time stamp in laravel?

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.


1 Answers

In order to attach the timestamps to each of the model relationships you need to chain the method ->withTimestamps().

So, for exam, in your case, it would be the following:

public function favorites()
{
    return $this->belongsToMany(User::class, 'favorites')->withTimestamps(); 
}

This would then attach the timestamps. Hope this helps you.

like image 198
Phorce Avatar answered Sep 30 '22 02:09

Phorce