I was reading this article to work out how to sort records in my database based on how many likes they have:
Laravel OrderBy relationship count
I came up with this which works:
$Book = Book::with('likes')->get()->sortByDesc(function($book_sort)
{
return $book_sort->likes->count();
});
Which is based upon this Book model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
public $timestamps = true;
protected $fillable = [
'title', 'author', 'category', 'featured', 'rating', 'description'
];
public function category()
{
return $this->hasOne('App\Cat', 'id', 'category_id');
}
public function likes()
{
return $this->belongsToMany('App\User', 'favourite_books')->withTimestamps();
}
public function total_likes()
{
return $this->likes()->count();
}
}
However now I am stuck on how I would paginate these results. Does anyone know?