I almost read all article in google and posts in stackoverflow, but I couldn't find the right solution or I don't get it. anyway, I want to make a search function in Laravel API, so I started with:
public function search(Request $request) {
$data = $request->get('data');
$search = Post::where('title', 'like', "%{$data}%")
->orWhere('user_id', 'like', "%{$data}%")
->get();
return response()->json([
'data' => $search
]);
}
This working fine, and by below URL return me data:
http://127.0.0.1:8000/api/search?data=22
{
"data": [
{
"id": 10,
"title": "some",
"created_at": "2019-11-02 07:56:40",
"updated_at": "2019-11-02 07:56:40",
"user_id": "22"
}
]
}
But I want to get data for each parameter like this, and also remove params from url, instead send as form data:
http://127.0.0.1:8000/api/search
form data:
{
user_id: 22
}
So what I tried so far is:
public function search(Request $request) {
$user_id = request('user_id'); // this return 22
$title = request('title');
$search = Post::where('title', 'like', "%{$title}%")
->orWhere('user_id', 'like', "%{$user_id}%")
->get();
return response()->json([
'data' => $search
]);
}
But it return all data, not just data with user_id-> 22, Any idea?
Result:
{
"data": [
{
"id": 8,
"title": "some",
"created_at": "2019-11-02 07:55:57",
"updated_at": "2019-11-02 07:55:57",
"user_id": "12"
},
{
"id": 10,
"title": "some",
"created_at": "2019-11-02 07:56:40",
"updated_at": "2019-11-02 07:56:40",
"user_id": "22"
},
{
"id": 11,
"title": "some",
"created_at": "2019-11-02 07:56:45",
"updated_at": "2019-11-02 07:56:45",
"user_id": "4"
},
{
"id": 12,
"title": "some",
"created_at": "2019-11-02 07:56:47",
"updated_at": "2019-11-02 07:56:47",
"user_id": "42"
}
]
}
I want it just return id 10 because it only data with user_id 22.
->orWheretowhereto make the condition asAND.->get()to->pluck('user_id')like this and you will get theuser_idonly