SomeController.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Foundation\Bus\DispatchesJobs;
  4. use Illuminate\Routing\Controller as BaseController;
  5. use Illuminate\Foundation\Validation\ValidatesRequests;
  6. use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Support\Facades\Input;
  9. use App\Post;
  10. use App\Tag;
  11. class SomeController extends BaseController
  12. {
  13. use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
  14. public function index(){
  15. $result = [];
  16. foreach(Post::all() as $post){
  17. $record = ["title" => $post->title,
  18. "text" => $post->text,
  19. "id" => $post->id];
  20. $record['commentCount'] = $post->comments()->count();
  21. $record['tags'] = $post->tags;
  22. $result[] = $record;
  23. }
  24. return view('post_index', ['posts' => $result]);
  25. }
  26. public function create(){
  27. return view('form', ['allTags' => Tag::all(), 'postTags' => []]);
  28. }
  29. public function edit($id){
  30. $post = Post::find($id);
  31. $postTags = [];
  32. foreach($post->tags as $tag){
  33. $postTags[] = $tag->id;
  34. }
  35. return view('form',['post' => $post,
  36. 'allTags' => Tag::all(),
  37. 'postTags' => $postTags]);
  38. }
  39. public function store(Request $req){
  40. $newRecord = new Post([ 'title' =>Input::get('title'), 'text' =>Input::get('text')]);
  41. $newRecord->save();
  42. return redirect(route('cntrl.index'));
  43. }
  44. public function update($id){
  45. $post = Post::find($id);
  46. $post->title = Input::get('title');
  47. $post->text = Input::get('text');
  48. $tagIds = Input::get('tags');
  49. $post->tags()->detach();
  50. $post->tags()->attach($tagIds);
  51. $post->save();
  52. return redirect(route('cntrl.index'));
  53. }
  54. public function destroy($id){
  55. Post::destroy($id);
  56. return redirect(route('cntrl.index'));
  57. }
  58. public function show($id){
  59. $post = Post::find($id);
  60. return view('post_show', ['post' => $post,
  61. "comments" => $post->comments()->orderBy('id')->get()]);
  62. }
  63. }