What I'm trying to do is to append the comments of each article to the articles object, but the problem is that I need to request different number of comments each time.
and for some reason I need to use mutators for that, because some times I request 50 articles and I don't want to loop through the result and append the comments.
So is it possible to do something like the following and how to pass the extra argument.
This the Model:
class Article extends Model { protected $appends = ['user', 'comments', 'media']; public function getCommentsAttribute($data, $maxNumberOfComments = 0) { // I need to set maxNumberOfComments return $this->comments()->paginate($maxNumberOfComments); } }
Here is the controller:
class PostsController extends Controller{ public function index() { //This will automatically append the comments to each article but I //have no control over the number of comments $posts = Post::user()->paginate(10); return $posts; } }
What I don't want to do is:
class PostsController extends Controller{ public function index() { $articles = Post::user()->all(); $number = 5; User::find(1)->articles()->map(function(Article $article) { $article['comments'] = $article->getCommnets($number); return $article; }); return Response::json($articles); } }
Is there a better way to do it? because I use this a lot and it does not seams right.