Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bobdebower's avatar

Api Route Question

I'am building a api using postman. I Created a a factory with the name Espa and Rule

i used Tinker to make the relation ship espa hasmany rule like this: Espa::factory()->hasRule(5)->create();

Works fine using tinker, But how do i create a route of this?

I have the Espa controller and the Rule contoller they are resourcefull.

this is my route for showing a espa {id}. in the Espa Rule is nested in it.

But i want to able to make a post request, creating rule in a Espa{id}.

I hope explained it well.

Here is my Espastore

 public function store(Request $request)
  {
    $espa = new Espa ();
    $espa->enabled = $request->enabled;
    if ($espa->save()) {
        return new EspaResource($espa);
    }
     }

Here is my Espa show 'with' showing rule in it

public function show($id)
{
    //get espa
    $espa = Espa::with(['rule'])->findorfail($id);
    //return a single espa as a resource
    return new EspaResource($espa);
 }

Final question, which one is better for a api?

//list a single espa Route::get('/espa/{id}', [EspaController::class, 'show']); // i currentley use this

I also saw people using it this way:

Route::get('/espas/{espa}', [EspaController::class, 'show']); // how does this work in the controller?

Why i ask because i want my routes/api.php to be clean. by using the resource route.

0 likes
6 replies
martinbean's avatar

@laradoel I think you might be looking for nested resource controllers, in which case your routes would look like /espa/{espa}/rules

bobdebower's avatar

thank for your respond, but how does this work. i used this: Route::resource('/espa/{id}/rules', EspaController::class); . i'am using a id

do i have do it this way?

Route::resource('/espa/{espa}/rules', EspaController::class);

Also how to make a post request this way?

like this? http://127.0.0.1:8000/api/espa/22/rules

martinbean's avatar

@laradoel Did you look at the documentation for nested resource controllers after I mentioned them…?

bobdebower's avatar

yeah i didn't but after 1 hour still not working, i tried everything. i don't know how to make the request in postman

Please or to participate in this conversation.