How do I tell my API to display a particular result based on another column?
e.g. localhost:8000/api/gadgets/{{id}}
Normally it returns the particular information of the specific gadget with that ID
and localhost:8000/api/gadgets/{{imei_code}}
does not return any value or an error whereas imei_code
is a column that I needed to pass as a GET request…
I’m using the normal resource controller
public function show(Gadgets $gadget) { $response = ['data' => new GadgetResource($gadget), 'message' => 'specific gadget']; return response($response, 200); }
Also I need help on how I can create like a search function in the controller.
Advertisement
Answer
You can specify the model key by scoping – check docs
Route::resource('gadgets', GadgetController::class)->scoped([ 'gadget' => 'imei_code' ]);
Than, when Laravel try to bind Gadget model in Controller – model will will be searched by key imei_code
.
This code equvalent of
Route::get('/gadget/{gadget:imei_code}');