Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Search API in Laravel

Search API in Laravel

In this tutorial, I will give you an example of the “How to Create Search API in Laravel“, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

search api in laravel using postman

Product Table :

We have created a products table and we have some products for testing in the table in the database.

search api in laravel

Product Model :

We have a Product Model, we will get data from it.

App\Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    protected $fillable = ['id','product_no','cat_id','name','description'];

}

We will search data or strings from our route and get this parameter from the search method in the controller.

Create Route :

routes\api.php

Route::get('search/{name}','ProductController@search');

Controller :

App\Http\Controllers\ProductController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;


class ProductController extends Controller
{
    function search($name)
    {
        $result = Product::where('name', 'LIKE', '%'. $name. '%')->get();
        if(count($result)){
         return Response()->json($result);
        }
        else
        {
        return response()->json(['Result' => 'No Data not found'], 404);
      }
    }
}

Setup Postman for API :

Postman is an API platform for building and using APIs. We have already Installed Postman for testing API you can use any platform for testing APIs.

Select the Get method here, and just put the URL here,

http://127.0.0.1:8000/api/search/{keyword}

After following these steps successfully, you are able to fetch related search keyword results from the products table.

product search api in laravel

product search api in laravel

no result found message in api in laravel

In this article, we learned “Create a product search API in Laravel”, I hope this article will help you with your Laravel application Project.

Also Read : Multiple Database Connection in Laravel.