Home > front end >  How to store multiple integer key with value in single column with laravel migration
How to store multiple integer key with value in single column with laravel migration

Time:03-10

enter image description here

In feedbacks table there would be a integer column
A user can input 1,4,5 as feedback. How to design this column in laravel migration ?


I am thinking of json column, which is not serving my purpose of integer column.

CodePudding user response:

You can use json column in your migration or has to move to pivot table.

$table->json('json_column_name');

After that If you need to use its relations you can use this package.

CodePudding user response:

If you don't want to use a many-to-many relation, you just could make the column as integer and use the model to control how the columns is stored

class Feedback extends Model{
   /**
   * list of types
   */
   const TYPES = [
       self::LEADERSHIP => 'Leadership',
       self::BOLDNESS => 'Boldness',
       self::EXTERNAL_MIND => 'External mind',
       ...
   ];

   // Define constants
   const LEADERSHIP = 1;
   const BOLDNESS = 2;
   const EXTERNAL_MIND = 3;
   ...
}

The migration

use App\Models\Feedback;
...
Schema::create('feedbacks', function (Blueprint $table) {
    $table->id();
    ...
    $table->tinyInteger('type')->default(Feedback::LEADERSHIP);
});

For validation

use Illuminate\Validation\Rule;
use App\Models\Feedback;
...
Validator::make($data, [
    'type' => [
        'required',
        Rule::in(Feedback::TYPES),
    ],
]);
  • Related