0

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.

3 Answers 3

1

You can`t do two similar URLs. I think your route for URL

localhost:8000/api/gadgets/{{imei_code}}

isn`t work. Also the order of the routes is important and route that defined firstly will be have higer priority then route that defined secondly. Because your routes /api/gadgets/{{id}} and /api/gadgets/{{imei_code}} is similar in this case only the one described earlier will be processed.

You can define another router and handler, for example:

localhost:8000/api/gadgets

That will return a list of gadgets by default and you can add filters for imei_code. For example:

localhost:8000/api/gadgets?imei_code=123

And your handler for the new route may be writed something like that:

public function showList(Request $request): GadgetResource
{
    if ($imeiCode = $request->query('imei_code')) {
        $list = Gadget::query()->where('imei_code', $imeiCode)->get();
    } else {
        $list = Gadget::query()->take(10)->get();
    }

    return GadgetResource::collection($list);
}

Or like alternative solution you can create diferent route for searching of gadgets exactly by imei_code to get rid of any route conflicts

localhost:8000/api/gadgets/by_imei/123

public function findByImei(Request $request): GadgetResource
{
    $imeiCode = $request->route('imei_code');
    $item = Gadget::query()->where('imei_code', $imeiCode)->first();

    return new GadgetResource($item);
}

Sign up to request clarification or add additional context in comments.

Comments

0

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}');

Comments

0

Try to change response

public function show(Gadgets $gadget)
{
    $response = ['data' => new GadgetResource($gadget), 'message' => 'specific gadget'];
    return response()->json($response);  
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.