Multiple Select with BelongsToMany relationship
I'm just recently using Filamentphp and need to get into the mindset of how it works.
I have two sql tables:
Article
Article_pivot_games
In article_pivot_games I have the columns:
- id
-article_id
-games_id
now I need a multiple select, where he fills in the select with the names of the games that have the article_id equal to the id of the article I am editing.
in the model Article.php
However, how do I tell the select to use that function? Also am I using the right method?
Before filamentphp I used a custom admin of my own, in which I had a column in Article with the id_games column containing "1,6,123,532," and I used this:
8 Replies
Yes, that should be all you need to do. Just provide the BelongsToMany relationship name and title attribute in the relationship() method and specify multiple(). Filament will handle managing the pivot table for you.
https://filamentphp.com/docs/3.x/forms/fields/select#integrating-with-an-eloquent-relationship
Re:
However, how do I tell the select to use that function? Also am I using the right method?You already did, in the releationship('games', 'name') call. That first argument is the name of the relationship method on your model.
thanks @cheesegrits i solved with:
Maybe it can help someone by taking it as an example
What's with the square brackets in the Select name?
Good point... I used to use a select2, and I needed it to save multiple data... I will remove it.
But now I have a doubt, Filamentphp when I create a new article and save the data, does it automatically create the data in the pivot table or do I need to do something special?
It does it automatically.
BTW, from the changes you made in your code to make it work, it looks like your issue may just have been that you weren't using Laravel conventions for naming. It really makes life easier if you stick to those, so foreign keys are always foo_id, and pivot tables are always bar_foo (singular names, sorted alphabetically). Then you don't have to remember to tell Laravel when you haven't used the convention.
sorry for such a late reply..
1. Did you make it work ?
2. If you did, when you visit the form, is it populated with the already selected values ?
I made it work, but after i visit the form again, there are no selected values. In Db, they are ok though.
Yes, you probably created the relationship wrong in filamentphp.