I use the same stack and by a glance this code should work. Can you describing the issue a bit more than "and it has failed". Does the input loose focus? Does it keep rerendering because of useEffect()? Is it slow as you arent doing any debounce?
How can I perform Live Search in Inertia with React and Laravel
I'm working on a Laravel project, and I'm using InertiaJS with ReactJS to render my views. I need to implement a live search on a datatable, but I have tried to implement the data filter on every keystroke and it has failed. I also need the search input to send data like localhost:8000/admin/users?search=some&value to the server. In my backend, I have implemented the query in the Index() method in my UsersController as below:
public function index()
{
// return User::paginate(10);
$query = User::query();
if(request('search')) return $query->where('name', 'LIKE', '%'. request('search') . '%')->orWhere('email',
'LIKE', '%'. request('search') . '%');
return Inertia::render('Admin/Users/Index', [
'users' => $query->orderByDesc('created_at')->paginate(10),
'roles' => Role::all(),
]);
// ddd(User::get('name'));
}
This is what I implemented in the onChange event for the search input, and the state:
export default function Index(props) {
const { users } = usePage().props;
// Laravel's pagination data object = data
const { data } = users,
[query, setQuery] = useState({
search: ""
});
useEffect(() => {
Inertia.get(route(route().current()), query, {
preserveState: true,
replace: true,
});
}, [query]);
return (
<>
<Input type="search" name="search" value={query} id="search" autoComplete="search"
className="mt-1 block w-full shadow-sm sm:text-sm" placeholder={`Search here...`}
handleChange={(e) => setQuery(e.target.value)}/>
<Table>
{... some data here ...}
</Table>
</>
);
}
I have tried searching everywhere, but there seems to be limited information on this. I tried to understand this from the VueJS side of things and tried to implement it but failed. Any help on this will be appreciated. Thanks, big time!
I solved this. I implemented two search methods: frontend with React, and backend with Laravel. I created a button that sends the request to the server to filter the data. I implemented the following code in my index method:
$search = $request->query('search');
return Inertia::render('Admin/Users/Index', [
'users' => User::query()->when($search, fn ($query) =>
$query->where('name', 'LIKE', "%{$search}%")->orWhere('email', 'LIKE', "%{$search}%")
)->orderByDesc('created_at')->paginate(10)->withQueryString(),
'roles' => Role::all(),
]);
This is what I have in the frontend. This method is an onClick event of a button:
const search = (e) => {
Inertia.get(
route(route().current()),
{ search: query },
{
preserveState: true,
replace: true,
}
);
}
Please or to participate in this conversation.