John Davidson

php - how to use Laravel 8 query builder like eloquent for searching

0 comments
Message:


I'm developing a simple CRM with Laravel 8 that needs to search in query 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.


I've tried:


Role::query();

but that didn't work either.


I've 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 not be sending the "q" or "gender" URL params.


PS: Sorry for my bad English :)



My Answer:
To use Laravel 8 query builder like Eloquent for searching, you can create a controller method that accepts the search query parameter and then use the query builder to search for the relevant data. Here's an example of how you can achieve this:

1. Create a controller method in your UsersController that accepts the search query parameter:

php
public function search(Request $request)
{
$query = $request->input('q');

$users = DB::table('users')
->where('name', 'like', '%'.$query.'%')
->get();

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


2. Define a route in your web.php file that points to the search method in your UsersController:

php
Route::get('/admin/users/supervisor', 'UsersController@search');


3. In your view file, you can create a form that submits the search query to the controller method:

html






4. Finally, you can display the search results in your view file:

html
@foreach($users as $user)

{{ $user->name }}


@endforeach


This is a basic example of how you can use Laravel 8 query builder like Eloquent for searching. You can customize the query builder methods based on your specific requirements and database structure.

Rate this post

3 of 5 based on 5719 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us