rmondesilva
rmondesilva

Reputation: 1792

Accessing parent value inside Eloquent Relation

In my controller,

User::find(1)->with('matches')->get()

And in the Model,

public function matches()
{
    $userAge = $this->age; // Trying to access something like this

    return $this->hasMany('App\Others', 'location', 'location')
                ->selectRaw('*, ('.$userAge.' = age) as match');
}

How can I access the User's age like $this->age? Or Is that even possible? I already tried to var_dump($this) to see what I can get, but no luck.

My original goal was to inner join the User and Others table/model. I have a query like this:

SELECT (a.age = b.age) as match
FROM user a 
LEFT JOIN others b ON a.location= b.location 
WHERE a.location = 'Somewhere' 

I know I can do it easily with Query builder, but I think it is better if I can do it using Eloquent/Relationships.

Hope you guys get my point.

I'm still new in Laravel.

Upvotes: 3

Views: 2843

Answers (2)

Alexey Mezenin
Alexey Mezenin

Reputation: 163788

You get it wrong. The relationship should look like:

public function matches()
{
    return $this->hasMany('App\Others', 'location', 'location');
}

Then get the user with related matches with:

$user = User::with('matches')->find(1);

And then you'll have access to user's age and matches:

User is {{ $user->age }} years old
@foreach ($user->matches as $match)
    {{ $match->id }}
@endforeach

Upvotes: 1

user320487
user320487

Reputation:

You can use accessors and mutators on Eloquent models for this.

public function getAgeAttribute () {
    // add custom query logic here
    ...
    return $queryResult->age;
}

Then your User model can access it's age attribute as an instance:

$user->age

or within the Model itself:

$this->age

https://laravel.com/docs/5.5/eloquent-mutators#accessors-and-mutators

Anytime you name a function on a Model starting with get and ending with Attribute, you create a mutator which allows to define custom attributes or modify what is returned from existing attributes.

Upvotes: 1

Related Questions