Wednesday, April 13, 2022

[FIXED] How to store some tags in Laravel and how can I technically store those tags using the same ID

Issue

My question is that is okay to do it ID or some integer in migrations and how to store multiple tags using the same ID in controllers?

Storing like this (storing multiple tags on the same ID):
ID TAG
1 LARAVEL
1 PHP

  Schema::create('table_test', function (Blueprint $table) {
            $table->integer('id')->unsigned();
            $table->string("tags")
        });

Solution

I'm not sure the reason why you want to save the tags with same id in that table, but technically we can do that.

To create a unique id for each time you insert. I recommend you use uuid

   Schema::create('tags', function (Blueprint $table) {
            $table->uuid('id');
            $table->string('tags');
   });

For each time when you insert, generate the uuid first

    // Generate uuid  
    $uuid = Str::uuid();

   // Insert to DB 
    DB::table('tags')->insert([
        ['id' => $uuid, 'tags' => 'Laravel'],
        ['id' => $uuid, 'tags' => 'PHP']
    ]);


Answered By - Chung
Answer Checked By - Timothy Miller (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.