Getting timestamp and other fields from Pivot table in laravel


Posted 8 months ago by Ryan Dhungel

Category: Eloquent Laravel

Viewed 718 times

Estimated read time: 2 minutes

Course of the day!

Laravel with React JS - Build Twitter Like Real Time Web App

Laravel with React JS - Build Twitter Like Real Time Web App

How to get the pivot table created at, updated at timestamps in carbon instance and also get other fields from the pivot table to update the status?

Accessing pivot table created_at time

Model

public function categories()
{
return $this->belongsToMany(Category::class)->withPivot('created_at');
}

View

@foreach ($product->categories as $category)
<p>{{ $category->title }} (Created at {{ $category->pivot->created_at }})</p>
@endforeach


To get carbon instance of the created_at field to the view

Model

public function categories()
{
return $this->belongsToMany(Category::class)->withTimestamps();
}


View

@foreach ($product->categories as $category)
<p>{{ $category->title }} (Added at {{ $category->pivot->created_at->diffForHumans() }})</p>
@endforeach

Accessing pivot table field and running updates

Terminal

php artisan make:migration add_visible_to_category_product_table --table=category_product

Migration

$table->boolean('visible')->default(0);

Model

public function products()
{
return $this->belongsToMany(Product::class)
// Get created_at updated_at fields
->withTimestamps()
// Get pivot table field visable
->withPivot('visible')
// Get only if the visable is set to true
->wherePivot('visible', 1);
}

Controller


Update category product visible status to true(1)


  • Previously from our model we were getting only those categories_products whose visible status is set to 1 or true
  • Now we need to get all the products_categories whose visible status might be true(1) or false(0)
$product->categories()orWherePivot('visible', 0)->updateExistingPivot($category->id, ['visible' => 1]);


The above orWherePivot method is necessary to get the invisible ones(0) so that we can update them to make visible(1) using updateExistingPivot method.