Laravel pagination is not working in search page - laravel

I am using laravel 5.1. This is my code,
routes.php
Route::any('users/search', array('as' => 'adminuserssearch', 'uses' => 'UsersController#adminSearch'));
UsersController.php
public function adminSearch(){
$input = Input::all();
if(!empty($input)){
$key = Input::get('key');
$users = User::where('users.name', 'like', '%'.$key.'%')
->orWhere('users.email', 'like', '%'.$key.'%')
->paginate(10);
return view('admin.users.search', ['users' => $users,'tag' =>$key]);
}
}
search.blade.php
{!! $users->render() !!} //Use this code for display pagination.
When I search for a user, the url is like,
http://myproject/admin/users/search?key=user
But when I click pagination link the url will be like,
http://myproject/admin/users/search/?page=2
the ?key=user section will be lost from the url. How can I fix this problem ?

You should append this param to your pagination links .
{!! $users->appends(['key' => $tag])->render() !!}

In Laravel 8 change your UsersController.php by adding ->withQueryString() to ->paginate(10) e.g
public function adminSearch(){
$input = Input::all();
if(!empty($input)){
$key = Input::get('key');
$users = User::where('users.name', 'like', '%'.$key.'%')
->orWhere('users.email', 'like', '%'.$key.'%')
->paginate(10)->withQueryString(); //add withQueryString()
return view('admin.users.search', ['users' => $users]);
}
}
Yourwelcome: Source

You can costumize the paginator URL using the setPath() method.
You can add it to your controller like this $users->setPath('custom/url');

A solution that worked for me:
https://laravel.io/forum/11-15-2016-ho-to-paginate-search-results
The accepted solution says:
in your view where you display pagination...
{{ $results->appends(Request::except('page'))->links() }}

Related

Laravel Pagination Page2 Links to Blank Page

I'm hacking this Laravel query, it returns this pagination fine for page 1, but the rest of the links go to blank filtered-search pages which should be more or the rest of the query results.
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Job;
use Carbon\Carbon;
class FilterJobsController extends Controller
{
/**
* Show a list of all of the application's users.
*
* #return Response
*/
public function index()
{
$bidded = request('bidded');
$state = request('state');
$city = request('city');
$contractor = request('contractor');
$job = request('job');
$subjob = request('subjob');
$jobs = DB::table('jobs')->where([
['bidded', '=', $bidded],
['state', '=', $state],
['city', '=', $city],
['contractor', '=', $contractor],
['job', '=', $job],
['subjob', '=', $subjob],
])->paginate(3);
//])->get(); <<<former working method
return view('jobs.index', compact('jobs')->with('links', $links));
}
}
?>
Blade file:
#extends ('layouts.master')
#section ('content')
<div class="jobs">
#foreach(array_chunk($jobs->getCollection()->all(), 3) as $page)
<div class="leftarrow">❰</div>
#foreach ($jobs as $job)
#include ('jobs.job')
#endforeach
<div class="pagenumbers">
{{ $jobs->links() }}
</div>
<div class="rightarrow">
<!-- <a href="{{ url('/jobs/') }}"> -->
❱
<!-- </a> -->
</div>
<div class="downarrowrow">
<div class="downarrow">❱❱</div>
</div>
#endforeach
</div>
#endsection
As stated, the pagination page 1 work but the links in the paginated list go to a blank page, just layout-blade, header and footer info, no furthered search returns.
Any hints as to why the "links" has no information, just a valid link, would be appreciated.
It might due the request data no longer available on the next link. The requested data mentioned here are:
$bidded = request('bidded');
$state = request('state');
$city = request('city');
$contractor = request('contractor');
$job = request('job');
$subjob = request('subjob');
To cater this issue, try append the request object into paginate response as following:
$jobs = DB::table('jobs')->where([
['bidded', '=', $bidded],
['state', '=', $state],
['city', '=', $city],
['contractor', '=', $contractor],
['job', '=', $job],
['subjob', '=', $subjob],
])->paginate(3)->appends($request->all()); // -----> This line
That is a goodtip, now my $request is being built with some kind of unwanted extra html characters I assume (2)
This is the first query Laravel built which works:
filterjobs?bidded=0&state=Arizona&city=Phoenix&contractor=GeneralContractor&job=Concrete&subjob=Material
(2) Here is what my $request attempt is doing, thus returning nothing because of the extra characters and a seemingly wacked out logic order for the query:
filterjobs?=bidded%3D0&1=state%3DArizona&2=city%3DPhoenix&3=contractor%3DGeneralContractor&4=job%3DConcrete&5=subjob%3DMaterial&page=2
This is how I built that garble:
$request = array(
['bidded'.'='.$bidded)],
['state'. '='. $state],
['city'. '='. $city],
['contractor'. '='. $contractor],
['job'. '='. $job],
['subjob'. '='. $subjob]);
And then appeneded it as you suggested:
$jobs = DB::table('jobs')->where([
['bidded', '=', $bidded],
['state', '=', $state],
['city', '=', $city],
['contractor', '=', $contractor],
['job', '=', $job],
['subjob', '=', $subjob],
])->paginate(3)->appends($request);;
//
urlendode, urldecode, or mysqi_escape_real does not help. And I have constructed that request in other ways but still get the unwanted characters which make the query invalid. And, if you look carefully, things are also out of order with the equal signs, it seems to have also juggled the string in the ether returning some dyslexic query for reasons I do not quite understand.
But it seems a solution in this direction may work, eventually, atleast page2 pagination link has a query.
Yes appending the query properly was the key, thanks.
$this->validate(request(), [
'bidded' => 'required',
'state' => 'required',
'city' => 'required',
'contractor' => 'required',
'job' => 'required',
'subjob' => 'required',
]);
return view('jobs.index', [
'jobs' => Job::where([
['bidded', request('bidded')],
['state', request('state')],
['city', request('city')],
['contractor', request('contractor')],
['job', request('job')],
['subjob', request('subjob')],
])->paginate(3)->appends([
'bidded' => request('bidded'),
'state' => request('state'),
'city' => request('city'),
'contractor' => request('contractor'),
'job' => request('job'),
'subjob' => request('subjob'),
])
]);

Passing Results from 2 Queries in a Single Route in Laravel 5

I am trying to get posts from all users, plus tasks from only the current user. All passed into a single page with a single function and route. It returns an error page instead.
Controller
public function getDashboard()
{
$user = Auth::user();
$userId = $user->id;
$posts = Post::orderBy('created_at', 'desc')->get();
$tasks = Task::where('employee_id', $userId )->get();
return view('dashboard', compact('posts', 'tasks'));
}
Route
Route::get('/dashboard', [
'uses' => 'PostController#getDashboard',
'as' => 'dashboard',
])->middleware('auth');
Blade/View
<div>
#foreach($tasks as $task)
<p data-taskId="{{ $task->id }}">{{ $task->task_body }}</p>
#endforeach
</div>
Looks like possibly a syntax issue, as compact should work fine. Try this in your controller:
return view('dashboard', compact('posts', 'tasks'));
Then in your view, make sure to use the variables and not the class name, and as Karl Hill said, it's used within (), not {{}}:
#foreach($posts as $post)
{{$post->nameOrWhatever}}
#endforeach
#foreach($tasks as $task)
{{$task->nameOrWhatever}}
#endforeach

Provide link of a page in laravel

I have a database of questions which are viewed in localhost:8000/questions/{id}. I have created a chatbot in the existing laravel project. Now, I want to provide the user with the link of the question.
For example, if I want the link to a question of id=55, then the bot has to reply me with the link localhost:8000/questions/55.
How do I do that?
web.php
Route::resources([ 'questions' => 'QuestionController', ]);
Route::match(['get', 'post'], '/botman', 'BotManController#handle');
QuestionController.php
public function show(Question $question) {
return view('question')->with('question', $question);
}
botman.php
use BotMan\BotMan\BotMan;
use BotMan\BotMan\BotManFactory;
use BotMan\BotMan\Cache\DoctrineCache;
use BotMan\BotMan\Drivers\DriverManager;
use App\Conversations\StartConversation;
DriverManager::loadDriver(\BotMan\Drivers\Web\WebDriver::class);
$cachedriver = new Doctrine\Common\Cache\PhpFileCache('cache');
BotManFactory::create(config('botman', new
DoctrineCache($cachedriver)));
$botman = app('botman');
$botman->hears('Hello|Hi',
function($bot) {
$bot->typesAndWaits(1);
$bot->startConversation(new StartConversation);
}
);
BotManController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use BotMan\BotMan\BotMan;
use BotMan\BotMan\BotManFactory;
use BotMan\BotMan\Messages\Conversations;
use App\Conversations\StartConversation;
class BotManController extends Controller {
public function handle() {
$botman = app('botman');
$botman->listen();
}
public function startConversation(Botman $bot) {
$bot->startConversation(new StartConversation());
}
}
first we get all the ids from the questions table:
$questions = DB::table('questions')->select('id')->where('body', 'like', '%' . $answer . '%')->get();
$ids here is a collection of id so for each id we must create a link:
$links = array();
foreach($questions as $question){
$links[] = route('questions.show', ['id' => $question->id]);
}
so now we have all links needed to return as answer, finish it using $this->say... as you wish
you may want to return the first link not all links then get the first id from the database and create link using it:
$question = DB::table('questions')->select('id')->where('body', 'like', '%' . $answer . '%')->first()
$link = route('questions.show', ['id' => $question->id]);
then return the answer using $this->say
I hope this helps

Search Method with pagination result

I made a search method (GET) with some filters, the only problem that i have is when i run the search result i get the results with pagination with the adresse like :
search?q=&type_licence_id=&activite_licence_id=&structure_id=8
when i click on page 2 for exemple i have :
search?page=2
So it's display me anymore the results from the search query.
Maybe i done something wrong on my controller ? Hope someone could help me , thanks a lot in advance
here my controller :
public function search(Request $request)
{
$structure = Structure::select('num_structure', 'nom_structure' , 'id')
->get()
->mapWithKeys(function($i) {
return [$i->id => $i->num_structure.' - '.$i->nom_structure];
});
$activite = ActiviteLicencie::pluck('lb_activite' , 'id');
$type_licence = Type_licence::pluck('lb_type' , 'id');
$query = Licencies::query();
$filters = [
'type_licence_id' => 'type_licence_id',
'activite_licence_id' => 'activite_licencie_id',
'structure_id' => 'structure_id',
];
foreach ($filters as $key => $column) {
$query->when($request->{$key}, function ($query, $value) use ($column) {
$query->where($column, $value);
});
}
$licencies = $query->paginate(10);
return view('licencie/recherche', compact('licencies' , 'structure' , 'activite' , 'type_licence'));
}
I use the following in my blade template:
{{ $licencies->appends(Request::all())->links() }}
It appends all your request parameters to the pagination.
Check 'Appending To Pagination Links' on https://laravel.com/docs/5.4/pagination#displaying-pagination-results for information
You could customize the Pagination URL by
$licencies = $query->paginate(10);
$licencies->setPath($request->fullUrlWithQuery());
Docs:
https://laravel.com/docs/5.4/pagination#displaying-pagination-results
https://laravel.com/api/5.4/Illuminate/Pagination/LengthAwarePaginator.html#method_setPath

laravel 5.2 pagination pretty url

I am Using Laravel 5.2
Is There a Way To Get a Pagination Pretty URL in Laravel 5.2?
http://localhost:8000/backend/admin_user?page=10&page=1
And What I Would Like To Get,How generate Link Pretty Url:
http://localhost:8000/backend/admin_user/10/1
So you can try something like that:
Route::get('test/{page}', function ($page) {
return User::paginate(2, ['*'], 'page', $page);
});
You can achieve this with three simple steps.
Register the route:
Note the question mark, this makes the size and page values optional;
Route::get('backend/admin_user/{size?}/{page?}', ['uses' => 'BackendController#adminUser']);
Implement this function in your controller:
Note the default values, $size = 10, $page = 1. This makes sure that you don't get an error if you navigate to the url without the pagination.
<?php namespace App\Http\Controllers;
use App\Models\AdminUser;
use Illuminate\Pagination\LengthAwarePaginator;
class BackendController
{
public function adminUser($size = 10, $page = 1)
{
$collection = AdminUser::all();
$users = new LengthAwarePaginator($collection, $collection->count(), $size);
$users->resolveCurrentPage($page);
return view(backend.admin_user);
}
}
Use in your view like this:
<div class="container">
#foreach ($users as $user)
{{ $user->name }}
#endforeach
</div>
{{ $users->links() }}

Resources