简体   繁体   中英

Search paginate laravel result

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'));        
}

I have a search function in my controller but it isn't working.

Method Illuminate\Database\Eloquent\Collection::paginate does not exist.

How to fix it?

Try this:

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

Also you have a typo in your "$request->nama"

The reason of the error because you are applying a filter on the paginated result ie

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

Try like this.

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'));        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM