How to create a Filament relationship (has many)
FilamentCreating a Filament PHP relationship is fairly trivial because there already is a php artisan 'make' command for it.
Let's learn by example:
php artisan make:filament-relation-manager AccountResource transactions amount lang-bash
In this case it should be obvious than an account can have many transactions. So creating this resource will link the records up. What's important when creating these relationship managers is that the first parameter is the parent of the records that you want to link up.
The 3rd parameter, namely 'amount', is defined as '...the name of the attribute that will be used to identify transactions.'
This is very confusing at first so let's use another example:
php artisan make:filament-relation-manager ExchangeResource symbols name lang-bash
In this case we have a stock market program that has many exchanges. Each exchange has many symbols. When we browse to the exchange, we want to see all the symbols.
Once you've generated the relationship, you'll receive this output:
Make sure to register the relation in `ExchangeResource::getRelations()`. lang-bash
So after having created this new resource, we navigate to the bottom of the Exchange Resource and add this:
public static function getRelations(): array { return [ RelationManagers\SymbolsRelationManager::class ]; } lang-php
Please remember for this to work you would have already have this pre-existing relationship in your model:
public function symbols(): HasMany { return $this->hasMany(Symbol::class); } lang-php
Now, when we browse exchanges in our application, we'll see the below. From there it should be pretty obvious where we need to use 'name' (look at the bottom by MSFT).