How to resolve BadMethodCallExeption in Laravel (IoC Container) - php

When I add Route::resource('api', 'ApiController'); to my app/Http/routes.php, I get this error:
BadMethodCallException Method [index] does not exist.
My api controller looks like this:
<?php
class ApiController extends BaseController
{
public function getIndex()
{
echo "No Access";
}
public function postIndex()
{
// content here ...
}
public function check_ban($user, $gameBit, $ip)
{
// content here ...
}
public function check_balance($userid, $gameid, $serverid)
{
// content here ...
}
public function purchase_item($xml)
{
// content here ...
}
public function LoginRequest($xml)
{
// content here ...
}
public function CurrencyRequest($xml)
{
// content here ...
}
public function ItemPurchaseRequest($xml)
{
// content here ...
}
}
My api should handle out game login request, buying items, ban check and so on, but I get the error described above.
How do I resolve it please?

When you are using following to declare a resourceful route
Route::resource('api', 'ApiController');
Then let Laravel generate methods for you so go to command prompt/terminal and run:
php artisan controller:make ApiController
This will create a ApiController resourceful controller in app/controllers directory and all the methods will be (Method's skeleton) created. To make sure which method listens to which URI and HTTP method, run php artisan routes from command prompt/terminal so you'll get the idea. Read more about resourceful controllers on Laravel website.
If you want to declare your own methods against HTTP verbs then create a RESTful controller and to create a RESTful controller you don't have to run any artisan command from terminal but declare the route using:
Route::controller('api', 'ApiController');
Then create methods prefixing with HTTP verbs for responding to that verb for example:
class ApiController extends BaseController {
// URL: domain.com/api using GET HTTP method
public function getIndex()
{
//...
}
// URL: domain.com/api/profile using POST HTTP method
public function postProfile()
{
//...
}
// ...
}
If you run php artisan routes then you will be able to see all the URIs and method mapping. Check RESTful controllers on Laravel website.

Related

Feature test for authenticated user with auth middleware missing

I have a class that sets auth middleware in controller, like this:
class MyController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
}
public function something()
{
dd(Auth::user());
}
}
And a test like this:
class MyControllerTest extends TestCase
{
public function testSomething()
{
$user = factory(User::class)->create();
$this->actingAs($user);
$this->get('api/something');
}
}
The expected output is a dump of the user.
Everything works as expected, both in real application and in feature test.
The problem begins here: If I remove this line: $this->middleware('auth:api'); the output is the dump of user in tests but in real application it gets null. This is a problem as I can't rely on feature test.
With actingAs() Laravel seems to authenticate the user under the hood and then the test pass but the application fails. Is this a bug or there is something I'm missing here?
Using Laravel 7.x
If I understand right - you want test "is route has middleware". Than add to your tests:
public function testAuth()
{
//without acting as
$this->get('api/something')->assertForbidden();
}
With this, you can be you can be sure that Auth::user() is not null.

Laravel 5 Implicit Route Not Resoving

Editing this post entirely as I realize that I did a poor job of explaining things as they are, and to reflect a few changes already implemented.
The issue: I have an app that has a normal front end, which works perfectly when accessed via app\public. I've added a backend and wish to use a different master layout. I have named the backend Crud. I created Crud\UserController and that has the following:
public function __construct()
{ $this->middleware('auth'); }
public function getIndex() {
return view('crud'); }
In my routes.php file I have the following:
Route::controller('crud', 'Crud\UserController');
I've tried placing that route inside and outside of the middleware group. Neither workds. I do have a file, crud.blade.php, that exists inside resources\views.
The issue is a 404 from apache every time I try to access app/public/crud. Specifically, this error:
The requested URL /app/public/crud was not found on this server.
I'm at a loss as to why the server is unable to find the route to crud.blade.php
ETA: The apache access log just shows a normal 404 when I attempt to access this page. The apache error log shows no errors.
The view() is suppose to point to a view file, that is something like example.blade.php which should contain the content you want displayed when the localhost:app/crud is visited. Then you can do view('example') without the .blade.php.
From your code, change
class UserController extends Controller{
//Route::controller('crud', 'Crud\UserController');
public function __construct()
{
$this->middleware('auth');
}
public function getIndex() {
return view('/');
}
}
to
class UserController extends Controller{
//Route::controller('crud', 'Crud\UserController');
public function __construct()
{
$this->middleware('auth');
}
public function getIndex() {
return view('crud'); // crud being your view file
}
}
I think you're mixing concepts. Trying to get here will always throw an error:
localhost://app/crud
To enter your app, just try to access:
http://localhost
appending a route you registered in your routes.php file. In your example, It'd be:
http://localhost/crud
If you register
Route::get('/crud', 'Crud\UserController#index')
Then you need an Index method inside UserController, which should return a view (in your example)
class UserController extends Controller{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('crud');
}
}
P.S: about Implicit controllers, you have the docs here.

How to call controller function without declared in Route in Laravel 5.1?

i want to call the controller => function without specifying in route in Laravel 5.1.
such as controller / function
Example: admin/delete
so i want to call the above controller's function without specifying in routes is their any way to do that?
Also, if it is possible then how to pass parameters to that function?
I think you are looking for RESTful Controllers.
So in your route file you only have:
Route::controller('admin', 'AdminController');
and in your controller:
class AdminController extends BaseController {
public function show($adminId)
{
//
}
public function destroy($adminId)
{
//
}
}

Laravel 5, how to run a specific method according to the URL received

In my routes files I have a bunch or routes for testing purposes:
/** testing controllers */
Route::get('viewemail', 'TestController#viewemail');
Route::get('restore', 'TestController#restore');
Route::get('sendemail', 'TestController#send_email');
Route::get('socket', 'TestController#socket');
Route::get('colors', 'TestController#colors');
Route::get('view', 'TestController#view_test');
Route::get('numbers', 'TestController#numbers');
Route::get('ncf', 'TestController#ncf');
Route::get('dates', 'TestController#dates');
Route::get('print', 'TestController#printer');
Route::get('{variable}', 'TestController#execute');
/** End of testing controllers */
I want to eliminate all those routes and simple use the name of the given URL to call and return the method:
I have accomplished that in this way:
Route::get('{variable}', 'TestController#execute');
And in my testing controller:
public function execute($method){
return $this->$method();
}
Basically what I want to know if Laravel has a built in solution to do this, I was reading the documentation but couldn't find any way to accomplish this.
From official documentation:
http://laravel.com/docs/5.1/controllers#implicit-controllers
Laravel allows you to easily define a single route to handle every
action in a controller class. First, define the route using the
Route::controller method. The controller method accepts two
arguments. The first is the base URI the controller handles, while the
second is the class name of the controller:
Route::controller('users', 'UserController');
Next, just add methods to your controller. The method names should begin with the
HTTP verb they respond to followed by the title case version of the
URI:
<?php
namespace App\Http\Controllers;
class UserController extends Controller
{
/**
* Responds to requests to GET /users
*/
public function getIndex()
{
//
}
/**
* Responds to requests to GET /users/show/1
*/
public function getShow($id)
{
//
}
/**
* Responds to requests to GET /users/admin-profile
*/
public function getAdminProfile()
{
//
}
/**
* Responds to requests to POST /users/profile
*/
public function postProfile()
{
//
}
}
As you can see in the example above, index methods will respond to the
root URI handled by the controller, which, in this case, is users.
You could add a route pattern for the endpoints you want to listen for. Route them to a controller action, and then inspect the request:
class TestController extends Controller
{
public function handle(Request $request)
{
$method = $request->segment(1); // Gets first segment of URI
// Do something…
}
}
And in your route service provider:
$router->pattern('{variable}', 'foo|bar|qux|baz');

Call function in Controller using URL

Im comming from CodeIgniter.
There if you had a controller like this:
class Article extends CI_Controller{
public function comments()
{
echo 'Look at this!';
}
}
You could access the comments() function using the URL like this: example.com/Article/comments
How could I do something similar in Laravel?
The way I do it right now is specifiying a route like this:
Route::get('/Article/comments}', 'ArticleController#comments');
But I was hoping for a more dynamic way to do it as I don't want to keep on creating new routes for every function
The recommended way of dynamically calling controllers methods via URL, for Laravel users, is via RESTful Controllers:
<?php
class ArticleController extends controller {
public function getComment()
{
return 'This is only accesible via GET method';
}
public function postComment()
{
return 'This is only accesible via POST method';
}
}
And create your route using telling Laravel this is a RESTful Controller:
Route::controller('articles', 'ArticlesController');
Then if you follow
http://laravel.dev/articles/comments
Using your browser, you should receive:
This is only accesible via GET method
The way you name your controllers methods (getComment, postComment, deleteComment...) tells Laravel wich HTTP method should be used to call those methods.
Check the docs: http://laravel.com/docs/controllers#restful-controllers
But you can also make it dynamic using PHP:
class ArticlesController extends Controller {
public function comments()
{
return 'Look at this!';
}
public function execute($method)
{
return $this->{$method}();
}
}
Use a controller like this one:
Route::get('Article/{method}', 'ArticleController#execute');
Then you just have to
http://laravel.dev/Article/comments
I'll recommend that you stick with the laravel's way to create REST controllers, because that way you can have control over what HTTP Verb is being called with the controller method. The laravel way of doing this is just to add the HTTP Verb in front of the controller method, for your method comments if you want to specify a GET request in Laravel the name of the method would look like getComments.
For example, if you need to do a GET request for the article/comments URI, and then to create a new comment you want to use the same URI with another HTTP verb, lets say POST, you just need to do something like this:
class ArticleController extends BaseController{
// GET: article/comments
public function getComments()
{
echo 'Look at this!';
}
// POST: article/comments
public function postComments()
{
// Do Something
}
}
Further reading:
http://laravel.com/docs/controllers#restful-controllers
Now for your specific answer, this is the Laravel way of doing what you requested:
class ArticleController extends BaseController{
public function getComments()
{
echo 'Look at this!';
}
}
and in the routes.php file you'll need to add the controller as follows:
Route::controller('articles', 'ArticleController');

Categories