Reputation: 29
Hello everyone recently i started a project on Laravel 7.x but i have some problems.
I made a search with laravel default pagination.
This is my code:
Search form
<form action="/search" method="GET">
<input type="text" name="k" id="k" value="" placeholder="Search...">
<button type="submit">Search</button>
</form>
Controller
public function get_search(Request $request)
{
$keyword = request('k');
$data = DB::table('posts')
->where('title', 'LIKE', '%$keyword%')
->orderBy('id', 'DESC')
->paginate(20);
return view('search', ['data' => $data]);
Route
Route::get('/search',['uses' => 'MainController@get_search', 'as' => 'search']);
View
@foreach($data as $item)
{{ $item->title }}
@endforeach
{{ $data->links() }}
So i'm getting url like /search?key=keyword&page=2
All i want is to make looks like /search/keyword/page/2/
Thanks!
Upvotes: 0
Views: 1268
Reputation: 11
Replace ->paginate(20)
by ->paginate(20, ['*'], 'page', $page)
It's not documented.
Upvotes: 1
Reputation: 29
Ok, i made what did u said above and when getting print_r($data)
on search blade i am getting this
Array
(
[current_page] => 1
[data] => Array
(
[0] => stdClass Object
(
[title] => keyword 1
)
[1] => stdClass Object
(
[title] => keyword 2
)
[2] => stdClass Object
(
[title] => keyword 3
)
[3] => stdClass Object
(
[title] => keyword 4
)
[4] => stdClass Object
(
[title] => keyword 5
)
[5] => stdClass Object
(
[title] => keyword 6
)
[6] => stdClass Object
(
[title] => keyword 7
)
[7] => stdClass Object
(
[title] => keyword 8
)
[8] => stdClass Object
(
[title] => keyword 9
)
[9] => stdClass Object
(
[title] => keyword 10
)
)
[first_page_url] => hxxp://xxxx.xxx/search/keyword?page=1
[from] => 1
[last_page] => 5
[last_page_url] => hxxp://xxxx.xxx/search/keyword?page=5
[next_page_url] => hxxp://xxxx.xxx/search/keyword?page=2
[path] => hxxp://xxxx.xxx/search/keyword
[per_page] => 10
[prev_page_url] =>
[to] => 10
[total] => 49
)
Shows the same results while i am replacing the url hxxp://xxxx.xxx/search/keyword/page/2/
Any URL outputs the same result, it's just changed the ?page=x, but the results are the same. basically the hxxp://xxxx.xxx/search/keyword/page/
2/ does nothing.
hxxp://xxxx.xxx/search/keyword/page/2/
?page=2 which i don't need to..Upvotes: 0
Reputation: 46
I suggest that you modify the routes/web.php file. Use route arguments
Route::get('/search/{keyword}/page/{page}', 'SearchController@index')->name('.search');
And then, on the controller,
public function index($keyword, $page){ //Receive parameters
$data = DB::table('posts')
->where('title', 'LIKE', '%$keyword%')
->orderBy('id', 'DESC')
->paginate(20);
return view('search', ['data' => $data]);
...
}
Upvotes: 0