Warm tip: This article is reproduced from stackoverflow.com, please click
laravel laravel-5 php rest

In laravel how to pass extra data to mutators and accessors

发布于 2020-03-27 10:27:11

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.

Questioner
Mustafa Dwekat
Viewed
76
305 2018-12-22 18:43

Judging from the Laravel source code, no – it's not possible to pass an extra argument to this magic accessor method.

The easiest solution is just to add another, extra method in your class that does accept any parameters you wish – and you can use that method instead of magic property.

Eg. simply rename your getCommentsAttribute() to getComments() and fire ->getComments() instead of ->comments in your view, and you are good to go.