Utiliser un repository dans une vue

Par lolotoobo, il y a 10 ans


Bonjour

Je cherche à afficher une liste d'images et pour chaque images le nombre de commentaires. Que se soient pour les images ou les commentaires je passe par des repositories.
Dans mon controller je fais $albums = $this->albumRepo->getAll(); afin d'avoir la liste des albums à afficher.

Le soucis est dans la vue :
Pour le moment je fais (qui marche)

<h4>{!! count($album->approvedComments) !!} comments</h4>

pour bien faire je devrais faire (qui ne marche pas)

<h4>{!! count($this->commentRepo->getAll($album->id, 'App\Models\Album')) !!} comments</h4>

Le $thiscorrespond au controller qui appelle la vue

Dans AlbumsController j'ai

public function __construct(AlbumRepository $albumRepo, CommentRepository $commentRepo)
{
    $this->albumRepo = $albumRepo;
    $this->commentRepo = $commentRepo;
}

public function index()
{
    $albums = $this->albumRepo->getAll();

    return view('albums.index', compact('albums'));
}

Merci de toute aide

3 réponses

Grafikart, il y a 10 ans

Cela ne marcherait pas en passant par une association ?

<h4>{!! count($album->comments->getAll()) !!} comments</h4>
lolotoobo, il y a 10 ans

Non, il me renvoie Method getAll does not exist ce qui me semble logique car $album->comments me renvoie les commentaires à partir du modèle alors que getAll() me renvoie aussi les commentaires mais du repository.

Dans mon modèle Album j'ai

public function comments()
{
    return $this->morphMany(Comment::class, 'commentable');
}
lolotoobo, il y a 10 ans

Je viens de trouver un truc horrible qui marche

Dans le constructeur AlbumsController je fais

    public function __construct(AlbumRepository $albumRepo, CommentRepository $commentRepo)
{
    $this->albumRepo = $albumRepo;
    $this->commentRepo = $commentRepo;
    view()->share('comments', $this->commentRepo);
}

Ainsi en ayant partagé la variable,
Dans ma vue je peux faire $comments->getAll()

Mais je reste client d'une vraie solution propre :)