TwigBridge icon indicating copy to clipboard operation
TwigBridge copied to clipboard

Accessing Eloquent relationships

Open lvismer opened this issue 9 years ago • 3 comments

Hi

Was wondering if the following should work with v0.6.1. It is basically accessing a belongsTo relationship on an Eloquent model.

Inside the Project model I have

public function projectNoType()
{
    return $this->belongsTo('App\Models\ProjectNoType', 'projectNoTypeID');
}

Then inside the view I try to access the member on the relationship

{{ project.projectNoType.name }}

I am getting the following exception:

Call to undefined method Illuminate\Database\Query\Builder::projectNoType()

Thanks

lvismer avatar Jun 03 '15 17:06 lvismer

Does project_no_type work? or projectNoType().get()?

barryvdh avatar Jun 04 '15 06:06 barryvdh

The following works,

{{ project.projectNoType().first().projectNoType }}

So for relationship access to work one must use the association relationship?

lvismer avatar Jun 04 '15 07:06 lvismer

As far as I'm aware this works in v0.9.0, assuming fixed in https://github.com/rcrowe/TwigBridge/commit/8ad1b509c966b286f923ac5087fd8bca1f539ebe - consider closing?

Test case: Ticket model is provided without loading the user relation (lazy loading)

Twig

{{ ticket.user.formatted_name }}

Classes

class Ticket extends Model 
{
     public function user()
     {
        return $this->belongsTo('App\Models\User', 'user_id');
     }
}

class User extends Model 
{
     public function getFormattedNameAttribute()
     {
          return '...';
     }
}

bytestream avatar Dec 15 '15 19:12 bytestream