How to display a complex relationship field for Laravel Backpack?

Viewed 32

I have a relationship Candidate -> Vacancy -> User

Candidate:

class Candidate extends Model
{
    public function vacancy()
    {
        return $this->belongsToMany(
            Vacancy::class,
            'vacancy_has_candidate',
            'candidate_id',
            'vacancy_id'
        );
    }
}

Vacancy:

class Vacancy extends Model
{
   public function candidate()
    {
        return $this->belongsToMany(
            Candidate::class,
            'vacancy_has_candidate',
            'vacancy_id',
            'candidate_id'
        );
    }

    public function manager() {
        return $this->hasMany(User::class, 'manager_id');
    }
}

User:

class User extends Authenticatable
{
    public function vacancy()
    {
        return $this->belongsTo(Vacancy::class, 'manager_id');
    }
}

I want to display in СRUD candidates the field of the relationship in which I call the manager method with the output of the field from the User model.

for example

class CandidateCrudController extends CrudController
{
....
    public function setupCreateOperation()
    {
        $this->crud->addFields([
              [
                   'name' => 'vacancy',
                   'type' => 'relationship',
                   'label' => 'Vacancy',
                   'model' => Vacancy::class, 
                   'entity' => 'manager', <- this method in Vacancy model
                   'attribute' => 'title', <- this column name in User
                   'ajax' => true,
              ]
         ]);
...

I get an error "Looks like field vacancy is not properly defined. The manager() relationship doesn't seem to exist on the App\Models\Candidate model"

I can’t understand why the backpack is looking for a manager method in Candidates, although in the model I indicated a Vacancy in which this relationship method exists. And how to do it right?

1 Answers

KorDEM.

You will not be able to achieve that as per Backpack Documentation:

  • entity is the method that defines the relationship on the current model, in your case App\Models\Candidate is the CrudController model. So entity there should be the vacancy relation.

If you are using Backpack\PRO paid addon you should be able to list the vacancies with the desired information by using something like:

$this->crud->addField([
   'name' => 'vacancy',
   'subfields' => [
     ['name' => 'manager']
   ]
]);

If you need aditional pivot fields you need to provide ->withPivot in the relation.

Check BelongsToMany documentation on Backpack website

Related