PostController.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Repositories\PostRepository;
  4. use App\Repositories\TagRepository;
  5. use App\Http\Requests\PostRequest;
  6. class PostController extends Controller
  7. {
  8. protected $postRepository;
  9. protected $nbrPerPage = 4;
  10. public function __construct(PostRepository $postRepository)
  11. {
  12. $this->middleware('auth', ['except' => ['index', 'indexTag']]);
  13. $this->middleware('admin', ['only' => 'destroy']);
  14. $this->postRepository = $postRepository;
  15. }
  16. public function index()
  17. {
  18. $posts = $this->postRepository->getWithUserAndTagsPaginate($this->nbrPerPage);
  19. $links = $posts->setPath('')->render();
  20. return view('posts.liste', compact('posts', 'links'));
  21. }
  22. public function create()
  23. {
  24. return view('posts.add');
  25. }
  26. public function store(PostRequest $request, TagRepository $tagRepository)
  27. {
  28. $inputs = array_merge($request->all(), ['user_id' => $request->user()->id]);
  29. $post = $this->postRepository->store($inputs);
  30. if(isset($inputs['tags']))
  31. {
  32. $tagRepository->store($post, $inputs['tags']);
  33. }
  34. return redirect(route('post.index'));
  35. }
  36. public function destroy($id)
  37. {
  38. $this->postRepository->destroy($id);
  39. return redirect()->back();
  40. }
  41. public function indexTag($tag)
  42. {
  43. $posts = $this->postRepository->getWithUserAndTagsForTagPaginate($tag, $this->nbrPerPage);
  44. $links = $posts->setPath('')->render();
  45. return view('posts.liste', compact('posts', 'links'))
  46. ->with('info', 'Résultats pour la recherche du mot-clé : ' . $tag);
  47. }
  48. }