How to call resource route Codeigniter 4 - codeigniter

Please I need help to enable me know how to map the resource route to http request.
for example am trying to call this url via axios
http://localhost/nmc/public/api/unregisteredpatients?userid=hen11#gmail.com
and i have created the following resource routes to call my api
//$routes->resource('api/unregisteredpatients/(:any)', 'UnregisteredPatients::show/$1', ['namespace' => 'Api']);
//$routes->get('api/unregisteredpatients/(:any)', 'UnregisteredPatients::show/$1', ['namespace' => 'Api']);
$routes->resource('api/unregisteredpatients/(:any)', ['controller' => 'Api/UnregisteredPatients']);
None of these was able to call my api method instead they all called the index() method, whereas I wanted it to call the show($id) method to enable me utilise the $id to fetch data.
public function show($id = null) {
.....
}
Please I need help

This solves it for me, though I couldn't have a way to capture query parameters but passing the parameter as a segment gives me an AFAIK solution.
$routes->match(['get'], 'api/unregisteredpatients/(:any)', 'Api\UnregisteredPatients::show/$1');

Related

Laravel routing with or without parameter in a group

For my application I am trying to create a few routes entries.
One entry to initialise the application and another for AJAX requests.
So my application should hit the initialise function if I type https.test.com/app/drive but also if I want to type some additional parameters at the end something like this: https:test.com/app/drive/specificTabA or https:test.com/app/drive/specificTabB
The problem is that when ever I type https.test.com/drive/specificTabNameA this clashes with the fetchData get route used by my AJAX call.
How can I access the initialise function when hitting this URl https.test.com/app/drive or also hitting something like this: https:test.com/app/drive/specificTabA or https:test.com/app/drive/specificTabB?
Route::group(['prefix' => 'drive'], function () {
Route::get('', 'CustomController#initialise');
Route::get('fetchData', 'CustomController#fetchData');
});
I've done some tests, and came with the following conclusion/solution:
Route::group(['prefix' => 'drive'], function () {
Route::get('fetchData', 'CustomController#fetchData');
Route::get('{param?}', 'CustomController#initialise');
});
CustomerController:
function initialise($param = null)
{
...
}
Note that by changing the order of the routes you will actually load the correct route.
When you visit /drive/fetchData it will load fetchData route
When you visit /drive/ it will load initialise route without arguments
When you visit /drive/xyz it will load initialise route with $param being xyz
Hope it helps :)
My friend I want to get your attention to Laravel docs https://laravel.com/docs/5.0/routing#route-parameters especially this one Route Parameters. You can tell router that this route can have parameter but also can not have it. Look at this example
Route::get('/{specific?}')
Now you can get this specific parameter in your Controller function after request
public function initialize (Request $request, $specific = null)
Set it default to null as this param can both be past and not, so it should have some default value.
Good luck ;)
The following should work for you:
Route::group(['prefix' => 'drive'], function () {
Route::get('fetchData', 'CustomController#fetchData');
Route::get('{path?}', 'CustomController#initialise')->where(['path' => '.*']);
});
This will allow the following path:
/drive => initialise
/drive/1 => initalize
/drive/1/2/3 => initalize
/drive/fetchData => fetchData
Adding ->where(['path' => '.*']) will route any path to initalize, e.g. /1, /1/2, /1/2/3.
If you only want to allow the path to be one level deep you can remove the where:
Route::get('{path?}', 'CustomController#initialise');

Laravel HTTP tests and request attributes

On my app I add attributes to the HTTP request so I can use it later. My app is a multi domain app (.co.uk, .dk, .de). I findout the domain in the RouteServiceProvider and add the detected language to the HTTP request so I can load the data according to the language and some other things.
I findout and add the website directly in the RouteServiceProvider:
$website = Website::where('domain', '=', request()->getHttpHost())->first();
request()->attributes->add(['website' => $website]);
Then in my controller or anywere else I just have to query the request
if (!$request->attributes->has('website')) {
\Log::error('Abort HTTP request: invalid website: ' . request()->getHttpHost());
abort('500');
}
$language = $request->attributes->get('website')->language();
When testing my app the code execute normally (website is found in the RouteServiceProvider) but then it break in the controller:
testing.ERROR: Abort HTTP request: invalid website
When looking at the attribute, the data are empty in controller but not in the RouteServiceProvider:
dump($request->attributes); // in RouteServiceProvider.php
Symfony\Component\HttpFoundation\ParameterBag {
#parameters: array:1 [
"website" => ...
dump($request->attributes); // in controller
Symfony\Component\HttpFoundation\ParameterBag {
#parameters: []
}
It looks like the request object in the controller is no longer the same. When dumping :
dump(['RouteServiceProvider' => request()]);
I get:
"RouteServiceProvider" => Illuminate\Http\Request {#385
And in controller:
dump(['Controller' => request()]);
"Controller" => Illuminate\Http\Request {#9379
How can I fix this?
First of all, I agree that this code should be in a middleware instead of the RouteServiceProvider.
If the language is you only concern here, I would suggest to just use app()->setLocale() instead of saving the website in your request. If you need other informations contained in the website object, I would suggest to store it in the session instead of the request because I think that this kind of information is more under the responsability of the session than the request, which is more designed to handle inputs, http verbs, headers, ...
This could solve your problem, if it is not the case, let us see more of your code and of the new dd() results

Pass data from routes.php to a controller in Laravel

I am attempting to create a route in Laravel for a dynamic URL to load a particular controller action. I am able to get it to route to a controller using the following code:
Route::get('/something.html', array('uses' => 'MyController#getView'));
What I am having trouble figuring out is how I can pass a variable from this route to the controller. In this case I would like to pass along an id value to the controller action.
Is this possible in Laravel? Is there another way to do this?
You are not giving us enough information, so you need to ask yourself two basic questions: where this information coming from? Can you have access to this information inside your controller without passing it via the routes.php file?
If you are about to produce this information somehow in your ´routes.php´ file:
$information = WhateverService::getInformation();
You cannot pass it here to your controller, because your controller is not really being fired in this file, this is just a list of available routes, wich may or may not be hit at some point. When a route is hit, Laravel will fire the route via another internal service.
But you probably will be able to use the very same line of code in your controller:
class MyController extends BaseController {
function getView()
{
$information = WhateverService::getInformation();
return View::make('myview')->with(compact('information'));
}
}
In MVC, Controllers are meant to receive HTTP requests and produce information via Models (or services or repositores) to pass to your Views, which can produce new web pages.
If this information is something you have in your page and you want to sneak it to your something.html route, use a POST method instead of GET:
Route::post('/something.html', array('uses' => 'MyController#getView'));
And inside your controller receive that information via:
class MyController extends BaseController {
function getView()
{
$information = Input::get('information');
return View::make('myview')->with(compact('information'));
}
}

Why aren't my controllers actions accessible with unit tests in Laravel

I have set up my route as such:
Route::controller('clients', 'Controllers\ClientsController');
Through this method I can easily access all the controller functions via post and get. However I cannot test them as easily.
public function testCantDeleteOtherAccountsClient()
{
Route::enableFilters();
$user = Models\User::find(1);
$this->be($user);
$response = $this->action('GET', 'ClientsController#getDelete');
$this->assertRedirectedToAction('ClientsController#getIndex');
}
This test results in the message
InvalidArgumentException: Route [ClientsController#getDelete] not defined.
The method accessible via url though. What am I missing?
Just tried this out myself (a route specified via the controller) your issue is that using action requires a named route. Controller routes do not currently support this as far as I'm aware of.
If you create a test route:
Route::get('test', array(
'as' => 'testName',
'uses' => 'ClientsController#getDelete'
));
And try
$this->action('GET', 'testName');
The test should pass, you can view all the routes with names via php artisan routes.
You may want to use $this->client->request() instead. You can check if a redirect occurred with:
$this->assertRedirectedTo("some\url");
Note that $this->call() is just an alias to $this->client->request().
I found changing it to use call instead of action worked for me:
$response = $this->call('GET', 'clients/delete/1');

Call a controller in Laravel 4

In Laravel 3, you could call a controller using the Controller::call method, like so:
Controller::call('api.items#index', $params);
I looked through the Controller class in L4 and found this method which seems to replace the older method: callAction(). Though it isn't a static method and I couldn't get it to work. Probably not the right way to do it?
How can I do this in Laravel 4?
You may use IoC.
Try this:
App::make($controller)->{$action}();
Eg:
App::make('HomeController')->getIndex();
and you may also give params:
App::make('HomeController')->getIndex($params);
If I understand right, you are trying to build an API-centric application and want to access the API internally in your web application to avoid making an additional HTTP request (e.g. with cURL). Is that correct?
You could do the following:
$request = Request::create('api/items', 'GET', $params);
return Route::dispatch($request)->getContent();
Notice that, instead of specifying the controller#method destination, you'll need to use the uri route that you'd normally use to access the API externally.
Even better, you can now specify the HTTP verb the request should respond to.
Like Neto said you can user:
App::make('HomeController')->getIndex($params);
But to send for instance a POST with extra data you could use "merge" method before:
$input = array('extra_field1' => 'value1', 'extra_field2' => 'value2');
Input::merge($input);
return App:make('HomeController')->someMethodInController();
It works for me!
bye
This is not the best way, but you can create a function to do that:
function call($controller, $action, $parameters = array())
{
$app = app();
$controller = $app->make($controller);
return $controller->callAction($app, $app['router'], $action, $parameters);
}
Route::get('/test', function($var = null) use ($params)
{
return call('TestController', 'index', array($params));
});
Laurent's solution works (though you need a leading / and the $params you pass to Request::create are GET params, and not those handled by Laravel (gotta put them after api/items/ in the example).
I can't believe there isn't an easier way to do this though (not that it's hard, but it looks kinda hackish to me). Basically, Laravel 4 doesn't provide an easy way to map a route to a controller using a callback function? Seriously? This is the most common thing in the world...
I had to do this on one of my projects:
Route::controller('players', 'PlayerController');
Route::get('player/{id}{rest?}', function($id)
{
$request = Request::create('/players/view/' . $id, 'GET');
return Route::dispatch($request)->getContent();
})
->where('id', '\d+');
Hope I'm missing something obvious.
$request = Request::create('common_slider', 'GET', $parameters);
return Controller::getRouter()->dispatch($request)->getContent();
For laravel 5.1
It's an Old question. But maybe is usefull. Is there another way.
In your controller: You can declare the function as public static
public static function functioNAME(params)
{
....
}
And then in the Routes file or in the View:
ControllerClassName::functionNAME(params);

Resources