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 :)
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
work with when() it's better
->when(true, function($query){$query->where('x', x);})
Related
I have a categorization in DB that a user has some clients, they are connected by user_id. At me, tables are shown in the dashboard that comes only clients that are registered by the currently logged-in user, but when I search by name or surname or mail at the table I see clients of other users.
This is the code?
public function render()
{
$user = Auth::user()->id;
if($this->searchTerm == ''){
return view('livewire.dashboard.user-management', [
'clients' => Client::where('user_id', '=', $user)->orderBy($this->sortField, $this->sortAsc)->paginate(8)
]);
}
else{
return view('livewire.dashboard.user-management', [
'clients' => Client::where('user_id', '=', $user)
->where('name', 'LIKE', '%'.$this->searchTerm.'%')
->orWhere('surname', 'LIKE', '%'.$this->searchTerm.'%')
->orWhere('email', 'LIKE', '%'.$this->searchTerm.'%')
->orderBy($this->sortField, $this->sortAsc)->paginate(8)
]);
}
}
How can I solve it?
You're mixing your and/or clauses. You want to make sure that user_id is always respected, but the rest are maybes. To fix that, pass the or clauses into a closure:
return view('livewire.dashboard.user-management', [
'clients' => Client::where('user_id', '=', $user)
->where(function($query) {
$query->where('name', 'LIKE', '%'.$this->searchTerm.'%')
->orWhere('surname', 'LIKE', '%'.$this->searchTerm.'%')
->orWhere('email', 'LIKE', '%'.$this->searchTerm.'%');
})
->orderBy($this->sortField, $this->sortAsc)->paginate(8)
]);
I am trying to create an items filter based on user selections. The filter works with GET and fetches it's parameters from the url.
I tried using the laravel's when function but the filter is not working, it keeps returning the same result set without adhering to the filtration rule I wrote for it.
I am on Laravel 8 and I used the method outlined on Laravel's Conditional Clauses.
I feel like the problem is with the whereBetween clause between even after hard coding values into it, the result was the same as before.
Any help to fix this is greatly appreciated in advance.
$queryString = $request->query();
$sortBy = null;
$minMaxArray = array();
if($queryString){
if (array_key_exists('sortby', $queryString)) {
$sortBy = ($queryString['sortby'] == 'lowest') ? 'ASC' : 'DESC';
}
if (array_key_exists('min', $queryString) || array_key_exists('max', $queryString)) {
$minMaxArray['min'] = preg_replace("/,/", '', $queryString['min']) ?: 0;
$minMaxArray['max'] = preg_replace("/,/", '', $queryString['max']) ?: 1000000;
}
}
$tutors = DB::table('users')
->join('tutors', 'users.email', '=', 'tutors.tutorEmail')
->where([
['users.name', 'like', '%' . trim($searchText) . '%'],
['tutors.tutorStrength', '<>', '-'],
['users.status', 'active'],
['users.gender', '<>', '-'],
['users.phone', '<>', '-'],
['users.role', 'tutor']
])
->orWhere([
['tutors.tutorStrength', 'like', '%' . trim($searchText) . '%'],
['users.status', 'active'],
['users.gender', '<>', '-'],
['users.phone', '<>', '-'],
['users.role', 'tutor'],
])
->orWhere([
['users.location', 'like', '%' . trim($searchText) . '%'],
['tutors.tutorStrength', '<>', '-'],
['users.status', 'active'],
['users.gender', '<>', '-'],
['users.phone', '<>', '-'],
['users.role', 'tutor'],
])
->when($minMaxArray, function ($subQuery) use ($minMaxArray){
return $subQuery->whereBetween('tutors.tutorFee', $minMaxArray);
})
->when($sortBy, function ($subQuery) use ($sortBy){
return $subQuery->orderBy('tutors.tutorFee', $sortBy);
}, function ($subQuery){
return $subQuery->inRandomOrder();
})
->select('tutors.tutorFee', 'tutors.feeType', 'tutors.tutorOccupation', 'tutors.tutorStrength', 'users.*')->distinct()->paginate(20);
I fixed it. Turned out that I needed to duplicate the when conditional clauses on each where and orWhere clause.
I appreciate Kamlesh Paul for trying to help.
i want to filter with like in laravel project and paginate with laravel paginate, i try this code
$search = $request->get('query');
$products= DB::table('products')
->where('nama_produk', 'LIKE', '%'.$search.'%')
->paginate(6);
when use this code nothing error but it return all of data in my database table and not filtered.
if i use this code
$search = $request->get('query');
$products= DB::table('products')
->where('nama_produk', 'LIKE', '%test%')
->paginate(6);
it Worked :(
can someone help me to solve this problem ?
This is my search controller :
public function search(Request $request){
$query = $request->query;
$search = Post::where('post_title', 'LIKE', "%$query%")->orWhere('post_body', 'LIKE', "%$query%")->orWhere('post_tags', 'LIKE', "%$query%")->orderBy('created_at')->paginate(10);
return view('front.search', ['posts'=> $search, 'query'=> $query]);
}
Hope this helps.
I would like to assign a group to users which have a role student and have also a particular selected group. There is a users table, which has pivot tables: role_user and group_user with roles and groups tables. Below is the code for the controller where I am trying to execute the query:
$this->validate($request, [
'add-group' => 'required',
'where-group' => 'required'
]);
$selectedGroup = $request->input('add-group');
$whereGroupId = $request->input('where-group');
$users = User::whereHas('roles', function($q) {
$q->where('name', 'student');
})->whereHas('groups', function($q) {
$q->where('id', $whereGroupId);
})->get();
$selectedGroup = Group::whereId($selectedGroup)->first();
$users->assignGroup($selectedGroup);
You need to use the orWhereHas clause for the second half of the query.
Secondly, your $whereGroupId variable is not in the inner-function's scope, add a use($whereGroupId) statement to include it in the function's scope.
$users = User::whereHas('roles', function($q) {
$q->where('name', 'student');
})->orWhereHas('groups', function($q) use ($whereGroupId) { // <-- Change this
$q->where('id', $whereGroupId);
})->get();
You had syntax error and a missing use to pass whereGroupId. I have no clue what assignGroup does, but this should fix the code you have.
$this->validate($request, [
'add-group' => 'required',
'where-group' => 'required'
]);
$selectedGroup = $request->input('add-group');
$whereGroupId = $request->input('where-group');
$users = User::whereHas('roles', function ($q) {
$q->where('name', 'student');
})
->whereHas('groups', function ($q) use ($whereGroupId) {
$q->where('id', $whereGroupId);
})->get();
$selectedGroup = Group::whereId($selectedGroup)->first();
$users->assignGroup($selectedGroup);
I understood that Laravel's Eloquent ORM queries generally had the structure
The model
Query Constraints
Fetch methods.
However, can someone tell me what this code would do?
$user = User::where('username', '=', $username)->where('active', '=', 1);
It seems to have 2 constraints, but no fetch method,
for example I would expect the query to have
->first() or
->update(array('key' => 'value') or
->delete()
or similar on the end?
The code only sets up the query with the two mentioned where clauses. This is useful when you want to add clauses depending on different conditions:
$user = User::where('username', '=', $username)
->where('active', '=', 1);
if ($filterByAge) {
$user->where('age', '>', $age);
}
if ($filterByHeight) {
$user->where('height', '>', $height);
}
return $user->get();
Or when you're applying them from, let's say, an array:
$wheres = [
'username' => 'Raphael',
'active' => true,
'height' => '173'
];
$user = User::query();
foreach ($wheres as $field => $value) {
$user->where($field, '=', $value);
}
return $user->get();