Public Function Index in Laravel Controller Using latest() Module and Search Feature

Rikzan Fernanda
Feb 27, 2021

Hello guys, this is my first writing and I will show you how to make index function in Laravel controller. This is simple source code which I like to use. Check it below.

public function index()
{
$data = Data::latest()->when(request()->search, function($data) {
$data = $data->where(‘content’, ‘like’, ‘%’. request()->search . ‘%’);
})->paginate(5);

return view(‘index’, compact(‘data’));
}

Explanation

Data::latest() is allowed you to get data from the last order.

For search feature using ->when() method, it will get data through sql and will display data according to what you are looking for.

And paginate() is method for make pagination or displays data with a certain limit.

Thank you…

--

--

Rikzan Fernanda
0 Followers

Web developer from Indonesia. I like to share my knowledge about programming especially web app.