Mar '14

Nested Resources in Laravel

Anyone who has tried to build a RESTful web service in Laravel will know all about resource routes. With a single route statement you can respond to all of your verbs (actions) for a given resource:

Route::resource('users', 'UserController');

Then create your UserController class with any/all of the following functions, as required:

GET /resource
public function index() {}

GET /resource/create
public function create() {}

POST /resource
public function store() {}

GET /resource/id
public function show($id) {}

GET /resource/id/edit
public function edit($id) {}

PUT /resource/id
public function update($id) {}

DELETE /resource/id
public function destroy($id) {}

Great! Works really well for basic CRUD, no worries there. However what if you want to run these actions for a resource that sits below another? e.g. Your users sit below separate clients and need to be managed independently. Well, despite no reference to this in the Laravel documentation, it turns out this is very easy indeed:

Route::resource('clients.users', 'UserController');

Then simply add your client ID to the URLs and function arguments as so:

GET /client/client_id/resource
public function index($client_id) {}

GET /client/client_id/resource/create
public function create($client_id) {}

POST /client/client_id/resource
public function store($client_id) {}

GET /client/client_id/resource/id
public function show($client_id, $id) {}

GET /client/client_id/resource/id/edit
public function edit($client_id, $id) {}

PUT /client/client_id/resource/id
public function update($client_id, $id) {}

DELETE /client/client_id/resource/id
public function destroy($client_id, $id) {}

And you’re done! Boom!

Leave a Reply