Using Laravel models, I have built the following structure
user-1
company-1
store-1
store-2
company-...
store-1
company-N
store-1
store-2
store-n
user-2
company-5
store-12
user-3
company-8
store-15
company-9
store-21
That reads: an user have N companies and each company have N stores.
I have the following routes for that
$api->resource('companies', 'App\Http\Controllers\v1\CompaniesController');
$api->resource('companies.stores', 'App\Http\Controllers\v1\StoresController');
Right now, my CompaniesController is listing the companies as follows:
public function index() {
return $this->response->collection(
JWTAuth::parseToken()->authenticate()->companies, new CompanyTransformer
);
}
Which I don't think it's appropriate, but it's a working code (for that I have posted a Code Review).
Now, going down the rabbit hole, we have the next controller: StoresController
public function index($company) {
$company = JWTAuth::parseToken()->authenticate()->companies->find($company);
if(empty($company))
throw new NotFoundHttpException();
return $this->response->collection(
JWTAuth::parseToken()->authenticate()->companies->find($company)->stores, new StoresTransformer
);
}
Here is where I'd say it's no longer an acceptable Working Code. In order to find all Stores from a given company, I have to find()
between the user companies a specific company and check if it's not null (it exists) so I can return the proper list of stores. Imagine when I have to list a child of Stores? And if I have child resource of that child? The more I go down, the more ifs I'll have to perform to make sure the user owns that resource.
Am I missing something here? How do people give a list of owned resource given an Authenticated user?