2

I am trying to create a relationship in laravel with timestamps. I have this app that allows customers to request a job to a marketplace. When a freelancer on the marketplace finds a job their interested in they propose to complete the job and a new row is queried into the freelancer table.

Here is the code creating the relation:

$marketplace->freelancers()->create([
   'request_id' => $id,
   'user_id' => $user->id
]);

Here is the Marketplace Model relationship code:

    /**
     * A request may have multiple freelancers
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function freelancers()
    {
        return $this->hasMany('App\Models\MainFreelancers')->withTimestamps();
    }

Here is the Freelancer Model relationship code:

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function mainMarketplace()
{
    return $this->belongsTo('App\Models\MainMarketplace');
}

When trying to run the very first code block I keep getting this Laravel Error: BadMethodCallException Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::withTimestamps()

In the short term, I just manually added a strtotime() but I'd prefer to utilize what Laravel offers. Does anyone have suggestions?

Note I have reference a previous stackoverflow question here: Timestamps are not updating while attaching data in pivot table But unfortunately it didn't help.

Solomon Antoine
  • 554
  • 1
  • 7
  • 14

2 Answers2

6

withTimestamps(); is used in Many to Many relationships where you want to declare that there are created_at and updated_at columns in the join table.

$withTimestamps Indicates if timestamps are available on the pivot table.

As the exception rightly points out, Illuminate\Database\Eloquent\Relations\HasMany does not have a withTimestamps() method.

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Relations/HasMany.html

Angad Dubey
  • 5,067
  • 7
  • 30
  • 51
0

If you want your pivot table to have automatically maintained created_at and updated_at timestamps, use the withTimestamps method on the relationship definition:

return $this->belongsToMany('App\Role')->withTimestamps();

Eloquent relationships.

In the case of a belongs to many relationship, withTimestamps() manages your timestamps for you automatically. But you are implementing a has many relationship, so you have direct access to the timestamps.

Int this case, you can use an accessor in your model to format the date:

public function getCreatedAtAttribute()
    {
        return date("l jS \of F Y h:i:s A", strtotime($this->attributes['created_at']));
    } 
Elisha Senoo
  • 3,489
  • 2
  • 22
  • 29