0

I'm creating a blog from scratch and I'm on rating system. The thing is I need to sort the blog posts depending on ratings. How do I accomplish this with these?

This is my article model:

class Article extends Model
{
    use HasFactory;

public function category()
{
    return $this->belongsTo(Category::class);
}
public function rating()
{
    return $this->hasMany(Rating::class);
}
}

And this is the rating model:

class Rating extends Model
{
    use HasFactory;
protected $guarded = ['id'];

public function user()
{
    return $this->belongsTo(User::class);
}


public function article()
{
    return $this->belongsTo(Article::class);
}

}

In the BlogController this is how I add ratings to the db:

public function article_rate(Request $request){
    $article = Article::find($request->article_id);
    Rating::updateOrCreate(
        ['article_id' => $request->article_id, 'user_id' => auth()->id()],
        ['rating' => $request->rating]
    );
    return redirect()->back()->with(compact('article'));
}
incbeatz
  • 91
  • 1
  • 9

0 Answers0