Advertisement
Guest User

blogpost search

a guest
May 22nd, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use Illuminate\Http\Request;
  6. use App\Blogpost;
  7. use App\User;
  8. use App\Comment;
  9. use App\Category;
  10.  
  11. class BlogpostController extends Controller
  12. {
  13. public function overview()
  14. {
  15. $blogposts = Blogpost::orderBy('created_at', 'asc')->get();
  16.  
  17. return view('blog.overview', [
  18. 'blogposts' => $blogposts
  19. ]);
  20. }
  21.  
  22.  
  23. public function detail($id)
  24. {
  25. $blogpost = Blogpost::findOrFail($id);
  26. return view('blog.detail', [
  27. 'blogpost' => $blogpost
  28. ]);
  29. }
  30.  
  31.  
  32. public function comments($id)
  33. {
  34. $blogpost = Blogpost::findOrFail($id);
  35. $comments = $blogpost->comments; // can be applied in Blade directly (!)
  36.  
  37. return view('blog.comments', [
  38. 'blogpost' => $blogpost,
  39. 'comments' => $comments
  40. ]);
  41. }
  42.  
  43. public function search(Request $request){
  44. //get params
  45. $terms = $request->terms;
  46. $from = $request->from;
  47. $to = $request->to;
  48. $category_id = $request->category_id;
  49.  
  50. //get categories
  51. $categories = Category::pluck('name','id');
  52. //add empty category
  53. $categories->prepend('select category');
  54.  
  55. //$blogposts = Blogpost::orderBy('created_at', 'asc');
  56. $blogposts = Blogpost::orderBy('created_at', 'asc');
  57.  
  58. if(!empty($terms)){
  59. $termArray = explode(' ', $terms);
  60. foreach($termArray as $term) {
  61. //$blogposts->where('title',$term)->orWhere('title','like','%',$term,'%');
  62. $blogposts->where(function($query) use ($term){
  63. $query->orWhere('content','like','%'.$term.'%')->orWhere('title','like','%'.$term.'%');
  64. });
  65. }
  66. }
  67.  
  68. //get posts between the set dates
  69. if(!empty($from) && !empty($to)){
  70. $blogposts = $blogposts->whereBetween('created_at',array($from,$to));
  71. }
  72.  
  73. //get posts with set category id if set
  74. if(!empty($category_id) && $category_id > 0){
  75. $blogposts = $blogposts->where('category_id',$category_id);
  76. }
  77.  
  78. $blogposts = $blogposts->get();
  79. return view('blog.search', [
  80. 'blogposts' => $blogposts,
  81. 'categories' => $categories,
  82. 'terms' => $terms,
  83. 'from' => $from,
  84. 'to' => $to
  85. ]);
  86. }
  87.  
  88. public function getResults($id){
  89.  
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement