2

I searched before posting and I found this

Preventing Laravel adding multiple records to a pivot table

However if I try that solution I got an exception regarding query builder use of contains()

I need to check if an item is already attached to a user in the pivot table so to prevent multiple posts:

this one is the line I tried:

if (!Auth::user()->collected_item()->contains($id)) {

 Auth::user()->collected_item()->attach($id);    

}

but as said that doesn't work. So I built a query to check if the line user_id / id exists already in db, if resulting var is empty attach item else print "already there".. this way works however can it be simplified?

Community
  • 1
  • 1
Chriz74
  • 1,410
  • 3
  • 23
  • 47
  • 1
    Possible duplicate of [Preventing Laravel adding multiple records to a pivot table](http://stackoverflow.com/questions/17472128/preventing-laravel-adding-multiple-records-to-a-pivot-table) – totymedli Feb 22 '17 at 17:05

1 Answers1

3

oh damn! I solved it changing:

if (!Auth::user()->collected_item()->contains($id))

to

if (! Auth::user()->collected_item->contains($id) )
Chriz74
  • 1,410
  • 3
  • 23
  • 47
  • 1
    Perhaps this would do without making that extra check using `contains()` first: `Auth::user()->collected_item()->sync([$id], $detach = false);`. Important note about 2nd param `$detach = false` is that `sync()` would otherwise remove all rows except the one having `$id`. – Oliver Maksimovic Oct 26 '15 at 19:07
  • Thanks but that would remove all the other items attached to the user. – Chriz74 Oct 26 '15 at 19:43
  • As I've already mentioned: passing `false` as the second argument to `sync()` does not detach other records. See Eloquent API: http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Relations/BelongsToMany.html#method_sync or http://stackoverflow.com/a/24211767/197487 – Oliver Maksimovic Oct 27 '15 at 19:14