mafortis
mafortis

Reputation: 7138

laravel sync method with uuid

I have 2 tables categories and posts and third table category_posts is pivot table to relate those two tables.

Issue

The problem is that I use uuid for my tables and when new row will add to category_posts it does not get uuid so second row will throw error as ids aren't unique (both are empty).

What I'm looking for is a way to add uuid in my sync method.

$post->categories()->sync($request->input('category_id'), false);

and uuid package I use is goldspecdigital which can generate new uuid with this code

\Ramsey\Uuid\Uuid::uuid4()->toString()

Question

How can I add generating uuid code into my sync method in order to create uuid for each row as they are adding to database?

PS

I have tried such code but obviously wasn't successful so I'm asking here :)

$post->categories()->sync([['id' => \Ramsey\Uuid\Uuid::uuid4()->toString()], $request->input('category_id'), false]);

Upvotes: 1

Views: 1263

Answers (1)

Sumit Wadhwa
Sumit Wadhwa

Reputation: 3227

can you try this:

$category_ids = (array) $request->input('category_id');

foreach( $category_ids as $category_id ) {
   $data_to_sync[ $category_id ] = [ 'id' => \Ramsey\Uuid\Uuid::uuid4()->toString() ];
}

$post->categories()->sync( $data_to_sync, false );

this is basically a way you pass additional data to a pivot table via the sync method. But I'm not sure if it works for primary id.

let me know if it doesn't work

Upvotes: 3

Related Questions