Laravel Pagination Page2 Links to Blank Page - laravel

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'),
])
]);

Related

Livewire Error: public property [message] must be of type: [numeric, string, array, null, or boolean]

I am getting this issue, and I don't understand what I am doing wrong as I did this same exact approach for another component on this site, and works perfectly....
ViewMessages.php
public $messages;
public function mount($messages)
{
$this->messages = $messages;
}
view-messages.blade.php
<div class="flex flex-col">
#foreach ($messages as $message)
{{$message->content}}
#endforeach
</div>
Everything works and it outputs all the messages correctly.
When I try and pass in a livewire component into the for each, it gives that error.
#foreach ($messages as $message)
#livewire('chat.show-message', ['message'=>$message], key('show-message-'.$message->id))
#endforeach
// ShowMessage.php
public $user;
public $message;
public $user_id;
public $content;
public function mount($message)
{
$this->message = $message;
}
Honestly am lost on what I am doing wrong, as I copied the exact same code and changed the variables that I used before. It works right now on the site when I do nested components.
<div class="flex flex-col space-y-4 py-4 overflow-y-auto">
#foreach ($chats as $chat)
#livewire('kanbans.show-sidebar-chat-message', ['chat'=>$chat], key('chat-'.$chat->id))
#endforeach
</div>
I redid this component already twice, and can't find any syntax issues or spelling errors. =/
The issue was with the DB Facade query
$messages = DB::select('SELECT * FROM chat_messages
WHERE (receiver_id = :auth_id and user_id = :user) OR (receiver_id = :user2 AND user_id = :auth_id2)',
['auth_id' => $auth_id, 'user' => $user->id, 'auth_id2' => $auth_id, 'user2' => $user->id]);
Although not sure yet how to pass in the $user->id but when I set the user id to #2, the livewire components work as intended.
public function view($user)
{
$user=User::where('id',$user)->firstOrFail();
$messages = ChatMessage::where(function ($query){
$query->where('user_id', '=', auth()->id() )
->where('receiver_id', '=', 2 );
})->orWhere(function ($query){
$query->where('user_id', '=', 2)
->where('receiver_id', '=', auth()->id() );
})->get();
return view('backend.chat.view-contact-chat',compact('user','messages'));
}

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

search form using laravel shows 'Call to a member function getNumCommentsStr() on a non-object'

i have made a search bar using laravel, but it did not succeed. it shows the error as said below. And it seems that something wrong with my post object. But i do not know where.
source code as follows, thanks for helping.
//the searchController for seach code
public function search(){
$keyword = Input::get('keyword');
if(empty($keyword)){
return Redirect::route('/');
//->with('message',array('type' => 'alert', 'content' => '不能为空'))
}
$posts = Post::where('content', 'like', '%'.$keyword.'%')->orderBy('created_at', 'desc')->paginate(10);
$tags = Tag::where('count','>','0')->orderBy('count','desc')->orderBy('updated_at', 'desc')->take(20)->get();
return Redirect::route('searchResults')->with('posts', $posts->toArray())->with('tags',$tags);
}
public function searchResults(){
return View::make('frontend.search.search',['posts' => Session::get('posts'),'tags' => Session::get('tags')]);
}
//search bar route
Route::get('/searchResults', array(
'uses' => 'SearchController#searchResults',
'as' => 'searchResults'
));
Route::post('/search', array(
'before' => 'csrf',
'uses' => 'SearchController#search',
'as' => 'search'
));
//search from
{{ Form::open(array('url'=>'/search','method' => 'post','class'=>''))}}
{{ Form::token()}}
<label for="docSearch">
<i class="fa fa-search"></i>
</label>
<div class="searchInput">
{{Form::text('keyword', '', array('class'=>'docsSearch', 'placeholder'=>'搜索论坛动态...'))}}
{{ Form::submit('提交',array('class'=>''))}}
{{Form::close()}}
//now i just wanna to get it like this:
#if(!$posts)
{{'<section class="oneQuestion">sorry,no content...</section>'}}
#else
#foreach($posts as $post)
<section class="oneQuestion">
<div class="askResult">
<!-- <i class="fa fa-question notSolved"></i>
<i class="fa fa-check solved" style="display:none;"></i> -->
#if($post->getNumCommentsStr() == 0)
<a href="{{URL::route('viewPost', array('id' => $post->id))}}#reviews" class="notSolved"><span class="post_comment_Num">{{$post->getNumCommentsStr()}}</span>
<span> 回答</span>
</a>
#else
<a href="{{URL::route('viewPost', array('id' => $post->id))}}#reviews" class="solved"><span class="post_comment_Num">{{$post->getNumCommentsStr()}}</span>
<span> 回答</span>
</a>
#endif
</div><!--
--><div class="titlePart">
<span>
{{$post->user->username}}
{{$post->created_at->diffForHumans()}}
</span>
<a href="{{ URL::route('viewPost', $post->id)}}">
{{-- {{ substr($post->content,0,200) }}... --}}
{{$post->title}}
</a>
<div class="tagWrapper">
#foreach ($post->tags as $tag)
<span class="askTag" title="">{{$tag->name}} </span>
#endforeach
</div>
</div>
</section>
#endforeach
#endif
<div class="forumLink">
{{$posts->links()}}
</div>
//it showed me an error:
**Call to a member function getNumCommentsStr() on a non-object**
and my getNumCommentsStr like:
public function getNumCommentsStr()
{
$num = $this->reviews()->count();
// if($num == 1){
// return "1";
// }
return $num;
}
code seems a lot but i wanna to make it clear so you can find any errors. Thanks again.
Edit 2
Thanks for NightMICU's suggest and I change
Redirect::route('searchResults')->with('posts', $posts->toArray())->with('tags',$tags);
to the following:
Redirect::route('searchResults')->with('posts')->with('tags',$tags);
THE result is without any alert any more, it just shows: sorry, no content...
And did not show any search result, any problem? Thanks
EDIT TWO
//delete the searchResult method, all in one search method so that i can return the view in right in the search method.
public function search(){
$keyword = Input::get('keyword');
if(empty($keyword)){
return Redirect::route('developer');
//->with('message',array('type' => 'alert', 'content' => '不能为空'))
}
$posts = Post::where('content', 'like', '%'.$keyword.'%')->orderBy('created_at', 'desc')->paginate(10);
$tags = Tag::where('count','>','0')->orderBy('count','desc')->orderBy('updated_at', 'desc')->take(20)->get();
return View::make('frontend.search.search',['posts' => $posts,'tags' => $tags]);
}
EDIT 3
there are two questions exsiting here.
ONE is that when i change to that ,it can output the result but all the result the database has. Not the keyword results.
Two is that when there are extra page, once i open the link http://localhost/html5lav/public/search?page=2, it just show an error:
No query results for model [Post].
The initial issue most likely has to do with the unusual way you are displaying the search results; by passing the Eloquent collections via session to another method, only to display the View. You were also converting the Post Eloquent collection to a regular array with ->toArray(), pagination requires a collection rather than an array.
The solution for that part:
public function search(){
$keyword = Input::get('keyword');
if(empty($keyword)){
return Redirect::route('/');
//->with('message',array('type' => 'alert', 'content' => '不能为空'))
}
$posts = Post::where('content', 'like', '%'.$keyword.'%')->orderBy('created_at', 'desc')->paginate(10);
$tags = Tag::where('count','>','0')->orderBy('count','desc')->orderBy('updated_at', 'desc')->take(20)->get();
return View::make('frontend.search.search')->with('posts', $posts)->with('tags', $tags);
}
After taking care of the initial issue, you reported that the pagination links are not working as expected - you click on Page 2 and do not have any Post results. If the route for the page where the user inputs a search term is also /search, there is a conflict. Instead, change the route that the search form posts to, perhaps /searchResults (which then loads the results using the search method). You may also want to consider using a GET rather than POST request, allowing users to bookmark their search results or share a link.
Regarding the issue of displaying all of the entries from the posts table, you need to review MySQL raw queries in Laravel. Swing by the documentation and look them up.

Laravel pagination is not working in search page

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() }}

generate link to pages in laravel issue

I have a problem with link in laravel.
I have this route:
$lingua = Request::segment(1);
Route::group(array('prefix' => $lingua), function()
{
Route::get('/', 'ItemController#menu');
Route::get('/{idcampo}/{idcat}','ItemController#show');
});
The first is language and request the 1st segment, and use as prefix. in /
THis is my ItemController Controller
public function menu()
{$lingua = Request::segment(1);
return View::make('index', ['categorie'=>DB::table('cat_nome')->join('lingua', 'cat_nome.id_lingua', '=', 'lingua.id') ->where('lingua.lingua','=',$lingua)->get(),
'campi' => DB::table('campo_nome')->join('lingua', 'campo_nome.id_lingua', '=', 'lingua.id') ->where('lingua.lingua','=',$lingua)->get(),
'lingua'=>$lingua,
]
);
}
public function show($camps,$cats)
{$lingua = Request::segment(1);
return View::make('categorie', ['categorie'=>DB::table('cat_nome')->join('lingua', 'cat_nome.id_lingua', '=', 'lingua.id') ->where('lingua.lingua','=',$lingua)->get(),
'campi' => DB::table('campo_nome')->join('lingua', 'campo_nome.id_lingua', '=', 'lingua.id') ->where('lingua.lingua','=',$lingua)->get(),
'dd' => DB::table('description')->join('lingua', 'description.id_lingua', '=', 'lingua.id')->where('lingua.lingua','=',$lingua)->where ('description.id_cat','=',$cats)->where ('description.id_campo','=',$camps)->select('description.descrizione')->get(),
'lingua' => $lingua,
]);
}
In index i query a the entries of a menu.
#foreach ($campi as $campo)
{{$campo->nome}}
<ul class="list-unstyled">
#foreach($categorie as $categoria)
<li> {{$categoria->nome}} </li>
#endforeach
</ul>
#endforeach
Now when i pass to the controller, i keep the menu visualized and i visualize the single entries of the database (the description).
My problem is that when i click the first time on the link, which appear to be:
language/id1/id2
I go in the right page, visualize the description of the product BUT now the link on the side menu became:
language/id1/language/id1/id2
But it should always be language/id1/id2 even when i am in Itemcontroller#show
The second time the link are generated in the side menu, something is added on the link, and i can't quite understand why.
You might try to use URL::to like this:
<a href="{{ URL::to($lingua. '/'. $campo->id_campo. '/'. $categoria->id_cat) }}">

Resources