2

I have the registered Comment model which has a User reference, like this:

public function user() {
    return $this->belongsTo('App\User');
}

This function returns an instance of a User, and that's correct, but I don't know how to register the User column the get que user property using Backpack. Instead, I'm get a JSON representation of my model:

enter image description here

So, how do I get a specific field from my relationship function?

Valeriy
  • 1,365
  • 3
  • 18
  • 45
llanfair
  • 1,845
  • 4
  • 27
  • 43

3 Answers3

2

Sounds like the select column is a perfect match for you. Just use it in your EntityCrudController's setup() method, like so:

$this->crud->addColumn([
   // 1-n relationship
   'label' => "User", // Table column heading
   'type' => "select",
   'name' => 'user_id', // the column that contains the ID of that connected entity;
   'entity' => 'user', // the method that defines the relationship in your Model
   'attribute' => "user", // foreign key attribute that is shown to user
   'model' => "App\Models\User", // foreign key model
]);

The "attribute" tells CRUD what to show in the table cell (the name, the id, etc).

tabacitu
  • 6,047
  • 1
  • 23
  • 37
  • Thanks @tabacitu. Your solution worked. The comments were also really useful. About the 'type' key, what 'select' means in this context? – llanfair Nov 06 '17 at 23:28
  • 1
    When defining a field, “type” tells crud what kind of field you want to show to the user. There are 44+ field types available in Backpack, check them out here - https://laravel-backpack.readme.io/docs/crud-fields – tabacitu Nov 09 '17 at 11:06
  • 1
    Oups you’re talking about columns. Same thing, here are the column types - https://laravel-backpack.readme.io/docs/crud-columns-types – tabacitu Nov 09 '17 at 11:07
0

If you do:

$user = $comment->user->user;

You'll get 'test'; (from your example)

It may seem confusing because your User model has a user attribute. Maybe you can call it 'name' instead of 'user'. That way you'll call it:

$username = $comment->user->name;

Remember to check if the relationship exists before calling a property on the related model.

if(!is_null($comment->user)) {
    $username = $comment->user->user;
}

Or:

$username = !is_null($comment->user) ? $comment->user->user : 'No user';
Eduardo Pacios
  • 1,855
  • 15
  • 19
0

If you need to get some field from deeper relation, you can use closure column type:

$this->crud->addColumn([
        'label'    => trans('backend.column_names.agency_linked_service'),
        'name'     => 'agency_service_id',
        'type'     => 'closure',
        'function' => function (AgencyLinkedServices $entry) {
            return $entry->agencyService->agencyCategory->title;
        }
    ]);