vendredi 23 février 2018

Laravel append attribute not working

My objective is to append average rating of each products so i can display in the front end

I have two tables one is products and another is reviews

My review model

class Review extends Model 
{

    protected $table = 'reviews';
    public $timestamps = true;

    use SoftDeletes;

    protected $dates = ['deleted_at'];
    protected $fillable = array('user_id', 'product_id', 'rating', 'feedback');

    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }

    public function product()
    {
        return $this->belongsTo('App\Models\Product');
    }

}

My product model

protected $appends = ['average_rating','my_rating'];


   // i added these accoceries inside class as per the laravel documentation
 public function reviews()
    {
        return $this->hasMany(Review::class);
    }


    public function getAverageRatingAttribute(){
        return round($this->reviews()->avg('rating'),1);
    }


    public function getMyRatingAttribute(){

        //check if user loged in
        if(Auth::check()){
            return round($this->reviews()->where('user_id',Auth::user()->id)->avg('rating'),1);
        }else{
            return round($this->reviews()->where('user_id',NULL)->avg('rating'),1);
        }
    }

So basically this should append average rating to my product when ever i call from the controller. But instead i m getting Only the fields available in product table. I worked with this before and worked fine back then but i do not understand why it is not working this time. Can anyone please help me? thank you.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2GGsFUx
via IFTTT

Aucun commentaire:

Enregistrer un commentaire