Search code examples
phpeloquenttwigslim

Cannot access Eloquent attributes on Twig


I am trying to access an Eloquent attribute with Twig in Slim, and getting an error.

I have a Field and a Type object, and the relationship is as follows

class Field extends \Illuminate\Database\Eloquent\Model {

protected $table = 'fields';

public function type()
{
    return $this->belongsTo('models\Type');
}

When doing {{ f }} (being f a field), the output is this:

{"field_id":"1","field_name":"Your name","form_id":"2","type_id":"1","placeholder":"Please give us your name"}

And when doing {{ f.type }}, the result is:

Message: An exception has been thrown during the rendering of a template ("Object of class Illuminate\Database\Eloquent\Relations\BelongsTo could not be converted to string") in "pages/editform.html" at line 97.

If I try to do {{ f.type.name }}, doesn't throw up an exception but doesn't print anything either.

If I do it in PHP

    $fields = $form->fields;
    var_dump($fields[0]->type->name);

The value gets output correctly.

Any ideas?, Thanks


Solution

  • I had the same issue and stumbled upon this question. After solving it myself, I thought I'd try to help you out.

    Try doing a Eager Load on the model:

    Field::with('type')->get()
    

    This should allow you to do the following with no other issues.

    {{ f.type }}
    

    See more info here: http://laravel.com/docs/4.2/eloquent#eager-loading