Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 623
angelocala94 Avatar asked Dec 05 '25 04:12

angelocala94


1 Answers

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 }}

like image 134
lukasgeiter Avatar answered Dec 06 '25 19:12

lukasgeiter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!