WordPress-Like Blog Laravel 5.7 and AdminLTE 3 (19) – Search Form
In this nineteenth part of creating WordPress-Like Blog using Laravel 5.7 and AdminLTE 3, we will :
- Create a Search Form for the Posts
Create Search Form
To begin with, you need to open frontend layouts in layouts/sidebar.blade.php and activate the search form and wrapped it into a form :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!-- Search Widget --> <form action="{{ route('blog') }}"> <div class="card my-4"> <h5 class="card-header">Search</h5> <div class="card-body"> <div class="input-group"> <input type="text" class="form-control" value="{{ request('term') }}" name="term" placeholder="Search for..."> <span class="input-group-btn"> <button class="btn btn-secondary" type="submit">Go!</button> </span> </div> </div> </div> </form> |
Add these lines to blog/index.blade.php to show the search term :
1 2 3 4 5 |
@if($term = request('term')) <div class="alert alert-info"> <p>Search Results For: <strong>{{ $term }}</strong></p> </div> @endif |
Next we will make the search form functional. Open the BlogController.php and modify the index() method :
1 2 3 4 5 6 7 8 9 10 |
public function index(){ $posts = Post::with('author') ->latestFirst() ->published() ->filter(request('term')) ->paginate($this->limit); return view("blog.index", compact('posts')); } |
Open App\Post.php and add a new scopeFilter() :
1 2 3 4 5 6 7 8 9 |
public function scopeFilter($query, $term){ //check if any term entered if($term){ $query->where(function($q) use ($term){ $q->orWhere('title', 'LIKE', "%{$term}%"); $q->orWhere('excerpt', 'LIKE', "%{$term}%"); }); } } |
Now your search term has worked perfectly.
Add this line to index.blade.php in pagination section :
1 2 3 4 |
<!-- Pagination --> <ul class="pagination justify-content-center mb-4"> {{ $posts->appends(request()->only(['term']))->links() }} </ul> |
Github commit.
Tambahkan tutorial untuk fitur komentar blog nya Master _/\_
ok
kasih thumbnail dong postnya hehe
Terima kasih feedbacknya