I have 2 tables categories
and posts
and third table category_posts
is pivot table to relate those two tables.
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()
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]);
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