Search code examples
phplaraveleloquentrelationships

Laravel Relationships can't access


I have 3 models: User, A, B and C.

User.php

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

A.php

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

B.php

public function cRelation(){
    return $this->hasOne('App\C');
}

Then, i execute my query and load the relationship

$tests = User::all();
$tests->load('a.b.cRelation');

Now, in my view file, if i print this:

@foreach($tests as $test)
    {{$test->a->b}}
@endforeach

I can see my c_relation magic property as expected. But if i try to access it nothing is printed.

Where am i wrong? Why if i print the parent object ($test->a->b), i can see the property but i can't print it?


Solution

  • Here's what's happening...

    When you just print a model in your template with {{ $test->a->b }}, the model is converted into JSON to make the output more readable.
    When converting a model to JSON, Eloquent by default changes the relationship names from camelCase to snake_case.

    However when you access a relationship from the model, you always use the method name so in that case {{ $test->a->b->cRelation }}