How to convert route params to query params in Lumen routes - lumen

I am building a REST api with Lumen and encountered a problem that I did solve, but perhaps there is a more elegant way.
I have two routes:
$app->get('profile/{profileId}', \App\Http\Controller\ProfileController::class . '#show');
and
$app->get('post', \App\Http\Controller\PostController::class . '#index');
A profile can have many posts, so I want to build a new route that is like this
$app->get('profile/{profileId}/post', \App\Http\Controller\PostController::class . '#index');
to get the posts of a profile.
But I don't want to pass the {profileId} as route param to the index action of the post controller, but as a query param.
To solve this, I changed the route to this
$app->get('profile/{profileId}/post', function ($profileId) use ($app) {
$controller = $app->make(\App\Http\Controller\PostController::class);
$request = $controller->getRequest();
$request->query->add([
'profileId' => $profileId,
]);
return $controller->index($request);
});
Had someone to do the same and has a better, more convenient way to do it?
I know e.g. that I could use the dingo package to do internal request from one controller to another, but I can not use it right now.

Related

How to Disallow User Access to CRUD Backend

I've got Backpack for Laravel installed and have been using it for some time as an admin back end on a project. I'm also using the spatie/permission module (might come with Backpack, can't remember) to create users for the front end.
Currently, all users are able to access both front end and back end regardless of the group they belong to. I'd like to change that so that only members in an "admin" group are able to access the back end. I've followed the instructions here for separating front end and back end sessions but that's not really what I want as all users are still able to access both sites of the project.
I'm guessing I need to add a guard to the CRUD routes but I'm finding it to be much harder than it should be. Any pointers on how to do this would be greatly appreciated. TIA.
You can create a new middleware and use it in your routes group for admin routes.
To create a new middleware use the php artisan command like so: (you can name the new middleware what ever you want:
php artisan make:middleware RequireAdminRole
Now, inside your new middleware, on the handle function you can have something like this that returns a 403 Forbidden error message:
public function handle($request, Closure $next)
{
$user = auth()->user();
if (!$user) return $next($request);
if (!$user->hasRole('Admin'))
{
// if your sessions are decoupled from the frontend
// you can even logout the user like so:
// auth()->logout();
abort(403, 'Access denied');
}
return $next($request);
}
Here we are using the hasRole method, but there are more that you can use. See the spatie/laravel-permissions documentation for more info.
Now, let's assign this middleware a 'name' so we can use it in our route groups for the admin. Inside the App\Kernel.php file, in the end, inside the $routeMiddleware array add it and give it a new, for example:
'isadmin' => \App\Http\Middleware\RequireAdminRole::class,
And finally, you can add this middleware to your admin routes group (which should be in custom.php file if you're using latest backpack 3.4 version) :
Route::group([
'prefix' => 'admin',
'middleware' => ['web', 'isadmin', config('backpack.base.middleware_key', 'admin')],
'namespace' => 'App\Http\Controllers\Admin',
], function () {
// your routes are here
});
Now all your requests to the admin routes should be protected by the user role check.
Please let us know how it went for you, and if you encountered any issues.
Best regards,
~Cristian

RESTFUL URLS in rails?

Hi I'm building REST api for an app, I have a requirement in URL
such that url should be something like this e.g
www.abc.com/api/param1/value1/param2/value2/param3/value3.... and so on
There are cases
case: The number of params are not limited it can change frequent
if today it is something like this
www.abc.com/api/param1/value1/param2/value2/param3/value3
tomorrow it can be like this
www.abc.com/api/param1/value1/param2/value2/param3/value3/param4/value4
Is there a configuration where once you configure the url pattern
and every thing go smooth
and in conrtoller params should contain this kind of key-value pair
{ "param1" => "value1","param2" => "value2","param3" => "value3"...and so on }
any suggestion !! how to achieve this ??
If your params are not fixed you can use wildcard in routing
for e.g
get 'items/list/*specs', controller: 'items', action: 'list'
def list
specs = params[:specs] # e.g, "base/books/fiction/dickens" #split it and place in a hash
end
Rails routing provides a way to specify fully custom routes with static and dynamic segments as explained in the Rails Routing Guide.
Your requirement should be achievable with
get '/api/param1/:param1/param2/:param2/...', to: 'controller#action'
You can use route scoping for this particular kind of problem . In other way it is nested routes
More details : http://guides.rubyonrails.org/routing.html#nested-resources
This is a example,
GET /magazines/:magazine_id/ads/:id/edit ads#edit
return an HTML form for editing an ad belonging to a specific magazine
I think this would be helpful for you.

CakePHP Custom REST Routes

I'm using CakePHP and Backbone.js as a frontend so I want to get CakePHP's REST routing working, but I don't really want to use the default REST routes.
For example, I want to be able to POST to http://example.com/cards/search.json and get a list of results in JSON, however I am getting a 200 status code back, and a blank response which makes me think the routing is not working properly.
I have tested my code using the default REST routes by chagning the search() method of my controller to add(), but I would prefer to be able to properly setup and use custom REST routes.
Router::connect(
"/cards/search",
array(
"[method]" => "POST",
"controller" => "cards",
"action" => "search"
)
);
Router::mapResources('cards');
Router::parseExtensions('json');
The code from my routes.php is above and I'm not entirely sure why it isn't working...either because the documentation on this is a little light, or I just don't understand routing very well.
You can get the json output in this url:
http://localhost:{port}/{api* name in config # app/core}/{controller name}/{things after api_ in function name}/{input parameters}.json
read more in here
You may have to alter the routing to change the name
api
to anything in
Configure::write('Routing.prefixes', array('master', 'api'));
in core.php in app/config
Feel free for a comment and also share your core.php in config for more explanation.

Can someone help me with POST method in Slim Framework?

I can set a GET method in Slim to get data from my database but my problem is the POST method, i don't know how to use it correctly. I do some code like:
$app->post('/login',function() use ($app){
$inputs = json_decode($app->request()->getBody());
$result = json_encode($inputs);
return $result;
});
I wanna make a login function by POST method but this is just an example I want to show the data that have been sent in the body by json. I used Advanced Rest Client to test but the result is always "null".
I'm new to Rest and Slim Framework too. Thanks for any helpful idea !
using return doesn't do anything in terms of viewing the output within that route callback function. use print, print_r, echo, $app->response->setBody('Foo'), or $app->response->write('Foo')
in terms of the post, did you try using $data = $app->request()->post() to get your data?

Zend Framework 2: How can I add in RESTful API a custom http method?

I'm trying to create a custom http method in RESTful API. I was reading the documentation and it is said that you can do it buy adding a simple action in controller and then for example conifg your route with child routes with action => action_name but in the code I have spotted addHttpMethodHandler() method in Zend\Mvc\Controller\AbstractRestfulController.php so in controller construct method I have added:
$add = function () {
return new JsonModel(array(
'id' => 2222,
));
};
$this->addHttpMethodHandler('someAction', $add);
var_dump($this->customHttpMethodsMap);
With the var_dump I can see that this new function is added but I just wonder how can I call it or maybe I'm missing the point.
Regards,
I actually wrote a blog post on this because I had so much trouble too.
The problem is that in addition to calling addHttpMethodHandler within the abstract restful controller, you also need to make sure that the Zend Request class knows that your http method exists.
Here is a link to a better explanation: http://richardbrock1.wordpress.com/2013/03/23/custom-http-methods-in-zf2/