Laravel上的表分页问题

时间:2018-10-16 06:20:14

标签: php laravel pagination

在laravel上分页时我遇到了一些麻烦。已经对表分页了。但是在查看页面中,数字并不正确。这就是它的样子:

https://i.stack.imgur.com/407Oo.png

另一个问题是当我按数字时,链接消失了,并给了我这个错误:

  

Symfony \组件\ HttpKernel \异常\   MethodNotAllowedHttpException没有消息

这是我的路线:

Route::get("/", "PagesController@welcome");

Route::post("/search", "PagesController@search")->name('search.route');

这是我的观点:

public function search(Request $request)
    {
        $q = $request->q;
        if ($q !== null && trim($q) !== ""){//here

            $estates = \DB::table('allestates')
                ->where("building_name","LIKE", "%" . $q . "%")
                ->orWhere("address","LIKE", "%" . $q . "%")
                ->orWhere("company_name","LIKE", "%" . $q . "%")
                ->orWhere("region","LIKE", "%" . $q . "%")
                ->orderBy('price')->paginate(10);


            if(count($estates) > 0){
                return view("search", compact('estates'))->withQuery($q);
            }

        }

        $estates = array();//here
        return view("search", compact('estates'))->withMessage("No Found!");//here
    }

另一件事是在控制器中,我无法将->paginate(10)添加到->get()中,它作为错误返回,例如:

  

方法Illuminate \ Support \ Collection :: paginate不存在。

我非常感谢您为解决此问题提供的帮助。谢谢! 顺便说一句是否连接,我不知道,但是我已经在公共场合删除/更改了“ boostrap”文件。

2 个答案:

答案 0 :(得分:0)

您不能使用paginate()方法访问DB外观。因为DB返回集合实例。但是paginate()是Model的方法。您需要根据集合实例手动创建分页器。试试这个:

$estates = \DB::table('allestates')
                ->where("building_name","LIKE", "%" . $q . "%")
                ->orWhere("address","LIKE", "%" . $q . "%")
                ->orWhere("company_name","LIKE", "%" . $q . "%")
                ->orWhere("region","LIKE", "%" . $q . "%")
                ->orderBy('price')->get();

$showPerPage = 10;

$perPagedData = $estates
            ->slice((request()->get('page') - 1) * $showPerPage, $showPerPage)
            ->all();

        $estates = new Illuminate\Pagination\LengthAwarePaginator($perPagedData, count($estates), $showPerPage, request()->get('page'));

来源:Manually Creating A Paginator

答案 1 :(得分:0)

我解决了问题。

在下面更改了控制器。

$q = $request->q;
$estates = \DB::table('allestates')
                ->where("building_name","LIKE", "%" . $q . "%")
                ->orWhere("address","LIKE", "%" . $q . "%")
                ->orWhere("company_name","LIKE", "%" . $q . "%")
                ->orWhere("region","LIKE", "%" . $q . "%")
                ->orderBy('price')->paginate(10);

return view("search", compact('estates','q'));

更改了视图

@if(count($estates))
    @foreach($estates as $estate)
        <!-- ... -->
    @endforeach
    {{ $estates ->appends(['q' => $q])->links() }}
@else
    <div class="alert">
        Not found!
    </div>
@endif

我还更改了下面的路线。

Route::any("/search", "PagesController@search")->name('search.route');

还为分页按钮添加了css。