Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Kaan33's avatar

Laravel groupBy Json data

Hello, I have a model and table named Gallery, column language in this table takes JSON data, Sample; With the Html Select option, the user can select and save multiple languages. and i want to group the records i want.

| id | title | language | | ------ | ------ |------ | | 1 | Apple | "[{"name":"Turkish","slug":"tr"},{"name":"Arabic","slug":"ar"}]" | | 2 | Banana |"[{"name":"English","slug":"en"},{"name":"Arabic","slug":"ar"}]" | | 3 | Home | "[{"name":"English","slug":"en"},{"name":"Turkish","slug":"tr"},]" | | 4 | About | "[{"name":"English","slug":"en"}]" | | 5 | Phone | "[{"name":"Arabic","slug":"ar"}]"| | 6 | Tablet | "[{"name":"Turkish","slug":"tr"},{"name":"Arabic","slug":"ar"}]" |

0 likes
34 replies
Kaan33's avatar

my model and database are the same

Sinnbeck's avatar

@Kaan33 He is suggesting that you instead add 2 new tables. languages and language_user. The first will hold all possible languages with id and language code, and the second is a pivot table that links the user with languages. This is called Many to Many

1 like
Tray2's avatar

@Kaan33 Then read it again.

What I say database model it's not the Eloquent Model.

The post cover how to think when you design the database structure, that is what the database model is.

The most important thing you should know, is that you should almost never store any data as json.

1 like
Kaan33's avatar

@Tray2 Thanks for your time, I created a 'languages' table as you said, but in the 'Gallery' model, language_id may come from more than one 'language_id', how can I take action for this?

Kaan33's avatar

@Tray2 language table | id | name | slug |

| ------ | ------ |------ |

| 1 | Turkish | tr |

| 2 | English |en |

| 3 | Arabic | ar |

gallery table

| id | name | image |

| ------ | ------ |------ | ------ |

| 1 | Cat | image |

| 2 | Dog| image |

| 3 | Banana| image |

gallery_languages table | id | language_id| gallery_id|

| ------ | ------ |------ | ------ |

The final state of the table is like the one above, so I now want to list the records etc. I'm really confused how to do it

Kaan33's avatar

@Tray2 The thing that confuses me is what will the 3rd table look like.

Sinnbeck's avatar

@Kaan33 You either have a pivot table (simple) or a morph table (advanced)

The pivot would look like this. It will be named gallery_language

| gallary_id | language_id | 

And the relationship on Gallery

public function languages()
{
    return $this->belongsToMany(Language::class);
}
Kaan33's avatar

@Sinnbeck language table | id | name | slug |

| ------ | ------ |------ |

| 1 | Turkish | tr |

| 2 | English |en |

| 3 | Arabic | ar |

gallery table

| id | name | image |

| ------ | ------ |------ | ------ |

| 1 | Cat | image |

| 2 | Dog| image |

| 3 | Banana| image |

gallery_languages table | id | language_id| gallery_id|

| ------ | ------ |------ | ------ |

The final state of the table is like the one above, so I now want to list the records etc. I'm really confused how to do it

Sinnbeck's avatar

@Kaan33 Thats just laravel convention. You have languages and galleries. That means this table is the alphabetically ordered singular version of the two

From the docs

To define this relationship, three database tables are needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names and contains user_id and role_id columns. This table is used as an intermediate table linking the users and roles.

Tray2's avatar

@Kaan33 No, according to the Laravel naming convention it's the singular form of both tables.

1 like
Kaan33's avatar

@Tray2 @sinnbeck well i produced it this way and the database created for me gallery_languages

php artisan make:model GalleryLanguage -mrc php artisan make:model Language -mrc

Sinnbeck's avatar

@Kaan33 Yes. Dont create a model for it. There is no need. Make a Gallery model with a galleries table :) 3 tables in total

1 like
Kaan33's avatar

@Sinnbeck maybe it will sound ridiculous to you but i'm really confused and i don't know what to do right now. Can you please take 5 minutes to delete all the tables and what should I do? :(

Sinnbeck's avatar

@Kaan33 Ok. Maybe there are some guides online. I can try expaining one more time.

You have 3 tables

  • galleries (Gallery model): This has a list of all galleries
  • languages (Language model): This is a list of all languages
  • gallery_language (No model): This is the table that binds the two other together. It has a column for each of the others. gallery_id and language_id. When you add a language to say gallery 22, with language 3, it will add a new record with ids 22 and 3, in a row.
Kaan33's avatar

@Sinnbeck

1-)

PS C:\xampp\htdocs\HelloWord> php artisan make:model Language -mrc

   INFO  Model [C:\xampp\htdocs\HelloWord\app/Models/Language.php] created successfully.  

   INFO  Migration [C:\xampp\htdocs\HelloWord\database\migrations/2022_12_07_130543_create_languages_table.php] created successf
ully.  

   INFO  Controller [C:\xampp\htdocs\HelloWord\app/Http/Controllers/LanguageController.php] created successfully.  

public function up()
    {
        Schema::create('languages', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
    }

2-)

PS C:\xampp\htdocs\HelloWord> php artisan make:model Gallery -mrc

   INFO  Model [C:\xampp\htdocs\HelloWord\app/Models/Gallery.php] created successfully.

   INFO  Migration [C:\xampp\htdocs\HelloWord\database\migrations/2022_12_07_131033_create_galleries_table.php] created successf
ully.

   INFO  Controller [C:\xampp\htdocs\HelloWord\app/Http/Controllers/GalleryController.php] created successfully.  

public function up()
    {
        Schema::create('galleries', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('image');
            $table->timestamps();
        });
    }

Are the tables I mentioned above created correctly? and How should I create the 3rd table?

Sinnbeck's avatar

@Kaan33 Seems two are

php artisan make:migration "add gallery language pivot table" 

And then

public function up()
    {
        Schema::create('gallery_language', function (Blueprint $table) {
            $table->foreignIdFor(Gallery::class)->onDelete('cascade');
            $table->foreignIdFor(Language::class)->onDelete('cascade');
            $table->timestamps();
        });
    }
Kaan33's avatar

@Sinnbeck I created the tables this way, but how do I write the pivot and the relationship between them? I would have learned because of you

Sinnbeck's avatar

@Kaan33 I gave you example earlier. On the Gallery model

public function languages()
{
    return $this->belongsToMany(Language::class);
}
1 like
Kaan33's avatar

@Sinnbeck

axios post metdhod Gallery

    "title" => "CamScanner 12-05-2022 10"
      "image" => 'image'
      "language" => "3,2"

GalleryController

/**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
		dd($request);
        $post = new Gallery();
        $post->title = $request->title;
        $post->image = 'img/home.jpg';
        $post->save();
    }

the result

      "title" => "CamScanner 12-05-2022 10"
      "image" => 'image'
      "language" => "3,2"

now how do i record here, $request->language

Sinnbeck's avatar

@Kaan33 something like

$post->languages()->attach(explode(',', $request->language));
Kaan33's avatar

@Sinnbeck error

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '[2' for column `laravel9_vue3_spa`.`gallery_language`.`language_id` at row 1 (SQL: insert into `gallery_language` (`gallery_id`, `language_id`) values (1, [2), (1, 1), (1, 3]))"
jlrdw's avatar

@Kaan33 Also I suggest taking some of the free lessons from here, @jeffreyway teaches laravel well. Also and just a suggestion, take some MySql tutorials and learn different types of queries.

Only suggestions..

1 like
Kaan33's avatar

@sinnbeck I solved the problem, but how do I group in the listing? i couldn't solve it

Sinnbeck's avatar

@Kaan33 what's the expected output? Say you have 3 galleries with 2 languages each

Kaan33's avatar

@Sinnbeck language:[ { name:'Turkish'; slug:'tr'; gallery:[ {name:'asdasd', image:'asdasd'}, {name:'asdasd', image:'asdasd'}, {name:'asdasd', image:'asdasd'}, ] }, {name:'English', slug:'en', gallery:[ {name:'asdasd', image:'asdasd'}, {name:'asdasd', image:'asdasd'}, {name:'asdasd', image:'asdasd'}, ]}, {name:'Arabic', slug:'ar', gallery:[ {name:'asdasd', image:'asdasd'}, {name:'asdasd', image:'asdasd'}, {name:'asdasd', image:'asdasd'}, ]}, ]

Please or to participate in this conversation.