Laravel relationships cannot 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 request and load the relationship
$tests = User::all();
$tests->load('a.b.cRelation');
Now, in my view file, if I type 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 going wrong? Why if I print the parent object ( $test->a->b
) I can see the property but I cannot print it?
source to share
Here's what's going on ...
When you just print the model to your template with {{ $test->a->b }}
, the model is converted to JSON to make the output more readable.
When converting a model to JSON, Eloquent changes the relationship names from camelCase to snake_case by default.
However, when you access the relationship from the model, you always use the method name , so in this case {{ $test->a->b->cRelation }}
source to share