Home > database >  how to use Laravel 8 query builder like eloquent for searching
how to use Laravel 8 query builder like eloquent for searching

Time:12-18

i'm developing a simple crm with Laravel 8 that needs to search in url string. my query string would be look like :

http://127.0.0.1:8000/admin/users/supervisor?q=john&gender=m

now the problem is how can i search in controller? i want to do like this:

    public function index (Request $request)
    {
        $role = getRoleCode($request->role);
        $roles = Role::where('role', '=', $role);

        if ($request->q) {
            $roles->where('name', 'like', "%$request->$q%");
        }
        if ($request->gender) {
            $roles->where('gender', '=', $request->gender);
        }

        $role->orderBy('id', 'desc')->paginate(20);
        return view('admin.users.index', [
            'roles' => $roles,
            'role_name' => config('settings.roles')[$role],
            'role_en_name' => $request->role,
            'q' => $request->q,
            'gender' => $request->gender
        ]);
    }

i wonder why its not working and what is the standard way to do this.

iv'e tried:

Role::query();

but didn't work either. iv'e also tried:

$roles = Role::where('role', '=', $role)
    ->where('name', 'like', "%$request->$q%")
    ->where('gender', '=', $request->gender)
    ->orderBy('id', 'desc')
    ->paginate(20);

this codes works perfectly but we may don't send the "q" or "gender" url params. ps: sorry for my bad English :)

CodePudding user response:

If you want to conditionally add where statements to your query you can use the if statements like you are attempting to do or use the when method of the Eloquent/Query Builder:

$roles = Role::where('role', $role)
    ->when($request->input('q'), fn ($query, $search) => $query->where('name', 'like', '%'. $search .'%'))
    ->when($request->input('gender'), fn ($query, $gender) => $query->where('gender', $gender))
    ->orderBy('id', 'DESC')
    ->paginate(20);

Laravel 8.x Docs - Queries - Conditional Clauses when

CodePudding user response:

work with when() it's better

->when(true, function($query){$query->where('x', x);})

CodePudding user response:

There is a mistake Mr Mohamed $roles instead of $role

//$roles->orderBy('id', 'desc')->paginate(20)...

CodePudding user response:

Your route should be like this :

Route::get('/admin/users/{role}', [YourController::class, 'index']);

Your index function will be like this :

    public function index (Request $request,$role)
    {
       //old line $role = getRoleCode($request->role);
        $role = getRoleCode($role);
       //...Your code 
   }
  • Related