jeudi 22 octobre 2015

Laravel: Get column value from first() result of relationship query

I'm trying to get a single column value from the first result of a Model's belongsToMany relationship query, as i'm returning the ->first() result of the relationship I was hoping $code->reward->title would work but it doesn't.

I get an Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation error

What I'm trying to do is the get the title of the current reward that is linked to a specific code - the code_reward pivot table has a valid_from and expires_at date as the reward linked to a code will change as time goes by, hence the need to get the currently active reward for that code.

Here's my code:

Model: Code

public function rewards()
{
    return $this->belongsToMany('App\Reward')->withPivot('valid_from', 'expires_at')->withTimestamps();
}



public function reward()
{
    $now = Carbon::now();
    return $this->rewards()
        ->wherePivot('valid_from', '<', $now)
        ->wherePivot('expires_at', '>', $now)
        ->first();
}

View: Codes/index

@foreach ($codes as $code)

    {{$code->id}}
    {{$code->reward->title}}

@endforeach

Any help is really appreciated!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire