Jane
Jane

Reputation: 17

make relation for value from array laravel

I have a table for data:

Schema::create('general', function (Blueprint $table) {
  $table->id();
  $table->string('key')->unique();
  $table->longText('value')->nullable();
  $table->timestamps();
});

When adding data, I get the following records in the database:

id: 2
key: country
value: ["Italy","Germany"]

Countries are now added to me through tags, like this:

$form->tags('value', __('Value'))->help('Use key `<b>Enter</b>` to add a new value')
  ->separators([';']);

The model has a function that receives and shares all values ​​with the key country:

public static function getCountries()
    {
        $country= self::where('key', 'country')->first();

        return explode(',', $country['value']);
    }

And then on the blade.php page I display these countries:

@foreach(App\Models\General::getCountries() as $country)
  <span>{{ $country }}</span>
@endforeach

The task is to attach a picture with a flag to each country.

I create a new model with migration to add a picture:

Schema::create('general_flags', function (Blueprint $table) {
  $table->id();
  $table->string('flag_image', 128);
  $table->timestamps();
});

My controllers are all done correctly and pictures are added and saved.

The main question is how do I create a relation of each value from the array with the desired flag, any ideas how to do this?

The problem is that I can’t change adding countries, so I have to work with what I have.

Upvotes: 0

Views: 198

Answers (1)

Taha Mohamed
Taha Mohamed

Reputation: 77

You can make new col in general_flags named country_code then when save countries_array in general save it as associative array ['country_code' => 'country name']. Or save image as associative array ['country_code' => 'Image'].
But, In my opinion you should make table for countries and every country has a flag.

Upvotes: 1

Related Questions