Showing relational data of a Filament resource
Asked Answered
C

1

6

I've started using Filament PHP for creating a Laravel based intranet application but stumbled across a question I couldn't answer myself using the official documentation:

What's the easiest way to show relational data inside the view page of a resource?

I have two resources ClientResource and ProjectResource which results in two Laravel relationships:

Client model:

public function projects(): HasMany
{
   return $this->hasMany(Project::class);
}

Project model:

public function client(): BelongsTo
{
   return $this->belongsTo(Client::class);
}

I have implemented a BelongsToSelect field inside project resource to assign a client:

Components\BelongsToSelect::make('client')
   ->relationship('client', 'first_name')
   ->required(),

Everything works fine so far, but (obviously) all I can see on the project's view page is the disabled select field showing the customer's first name. I'd like to have all related fields listed. Have I missed something crucial in the documentation or what's the best way to approach this?

I've had a look into the RelationManager but it seems there is only a belongsToMany relationship (no belongsTo).

Claudineclaudio answered 11/6, 2022 at 15:0 Comment(0)
A
6

This can also be done with a select component by specifying a relation like this:

    Select::make('client_id')
      ->relationship('client', 'first_name');

You also have access to the eloquent query builder instance to play with like so:

    Select::make('client_id')
      ->relationship('client', 'first_name', 
        fn (Builder $query) => $query->where('status', 'actif'))
    );

Document reference: https://filamentphp.com/docs/2.x/forms/fields#populating-automatically-from-a-relationship

Alverta answered 5/10, 2022 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.