Search code examples
arrayslaravelobjecteloquent-relationship

how to access multiple array elements in blade file laravel


Output

Rating model

class Rating extends Model
{
    protected $fillable = [
        'owner_id', 'toilet_id','user_id','rating','desc',
    ];

    public function toilet()
    {
        return $this->belongsTo(ToiletInfo::class);
    }
}

ToiletInfo model

class ToiletInfo extends Model
{
    protected $fillable = [
        'owner_id', 'toilet_name','price','complex_name','address','toilet_lat','toilet_lng','status',
    ];

    public function owner()
    {
        return $this->belongsTo(ToiletOwner::class);
    }

    public function ratings()
    {
        return $this->hasMany(Rating::class,'toilet_id');
    }
}

RatingController

public function index()
{

    return $toilets = ToiletInfo::with('ratings')->get();

    //return view('admin.rating',compact('toilets'));
}

enter image description here

I want to get the average of rating but how to access elements inside ratings[]

Or help me improve the method I am using to get ratings for toilets that are reviewed by users


Solution

  • From what I understand from your question you want to get the average rating.

    In your ToiletInfo model, add a new method:

    public function getAverageRating()
    {
        $ratings = $this->ratings;
        $count = $ratings->count(); // total count
        $total_ratings = $ratings->sum('rating'); // add the 'rating' for all rows
        return $total_ratings / $count; // average
    
    }
    

    In your blade file, you can simply do

    $toilet->getAverageRating()
    

    Which will give the average rating.