搜索分页laravel结果

时间:2019-10-06 00:53:05

标签: php laravel laravel-5 eloquent

public function cari_user_status(Request $request)
{       
    $users = User::orderBy('created_at', 'DESC')->paginate(10);

    if ( ! empty($request->nama))
    {
        $users = $users->where('name', $request->nama)->paginate();
    }

    return view('users.index',  compact('users'));        
}

我的控制器中具有搜索功能,但无法正常工作。

  

方法Illuminate \ Database \ Eloquent \ Collection :: paginate不   存在。

如何解决?

2 个答案:

答案 0 :(得分:0)

尝试一下:

$users = User::latest()
    ->when( ! empty($request->get('name')), function ($query) use ($request) {
        return $query->whereRaw("UPPER(name) LIKE '%" . strtoupper($request->get('name')) . "%'");
    })
    ->paginate(10);

return view('users.index', [
    'users' => $users,
]);

“ $ request-> nama”中也有错字

答案 1 :(得分:0)

由于对分页结果(即

)应用了过滤器而导致的错误原因
$users = User::orderBy('created_at', 'DESC')->paginate(10);
if ( ! empty($request->nama))
{
    // Problem is here $users is a collection of paginated result
    $users = $users->where('name', $request->nama)->paginate();
}

尝试这样。

public function cari_user_status(Request $request)
{       
    $users = (new User())->query(); 

    if ( ! empty($request->nama))
    {
        $users->where('name', $request->nama);
    }

    $users = $users->orderBy('created_at', 'DESC')->paginate(10);

    return view('users.index',  compact('users'));        
}