I'm making a reactjs that is connected to a restful api server using codeigniter 4. I want to only show the data where the field username
and full_name
contains a query string q
this is how my code looks like more or less:
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\UserModel;
class Users extends ResourceController
{
use ResponseTrait;
public function index()
{
$model = new UserModel();
$data = [];
// example uri: http://localhost:8080/users?q=asd
$qs = $_SERVER['QUERY_STRING'];
parse_str($_SERVER['QUERY_STRING'], $_GET);
$searchStr = empty($_GET['q']) ? '' : $_GET['q'];
if ($searchStr)
{
$data = $model->group_start()
->like('username', $searchStr)
->or_like('nama', $searchStr)
->group_end()
->findAll();
}
else
{
$data = $model->findAll();
}
return $this->respond($data);
}
}
when the search box in the react js app is empty, all the data is being shown correctly.. but when the search box is not empty, the $data
returns an empty array.. is the problem around the group_start()
part? how should I fix this?
thanks in advance
My Answer:
In CodeIgniter 4, you can use the `like` method in the `where` clause to search for records that contain a specific string in a particular field. Here's an example of how you can implement this in your RESTful API controller:
php
public function searchUsers($query)
{
$model = new UserModel();
$users = $model->like('username', $query)
->orLike('full_name', $query)
->findAll();
return $this->respond($users);
}
In this example, we are using the `like` method to search for records where the `username` field or the `full_name` field contains the query string `$query`. The `orLike` method is used to search for records where either of the fields contains the query string.
You can then call this method in your API endpoint to retrieve the filtered data based on the query string.
Rate this post
3 of 5 based on 8548 votesComments