For laravel API I have write the test cases. But whenever I am running the test cases it always failed with below error,
1) Tests\Feature\CompanyTest::orgTest
Expected status code 200 but received 404.
Failed asserting that 200 is identical to 404.
After adding the $this->withoutExceptionHandling(); to testcase code it return the below error,
1) Tests\Feature\CompanyTest::orgTest
Symfony\Component\HttpKernel\Exception\NotFoundHttpException: POST domainname/index.php/api/company
/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithExceptionHandling.php:126
/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:415
/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:113
/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:507
/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:473
/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:332
/tests/Feature/CompanyTest.php:21
My Code in Test File is,
public function orgTest()
{
$requestData = ["organizationId" => 10,"offset"=>1,"limit"=>10,"notificationId"=>""];
$response = $this->withoutExceptionHandling();
$response->postJson('/index.php/api/company',$requestData);
$response->assertStatus(200);
}
I have googled the error and tried many solutions but unable to succeed. Anyone please let me know whats the issue.
It is a 404 error, so your webpage is not found :
Symfony\Component\HttpKernel\Exception\NotFoundHttpException: POST domainname/index.php/api/company
Bad way to go, post to /api/company or with /index.php/api/company but not with "domainname" !
If it is not working, check your route config for that api route. Are your controller and action declared well ?
By default, laravel's routing does not explicitly show that it is a php file rather than it has dedicated endpoints which you decide on the routing file. So index.php shouldn't be a valid route for laravel.
A 404 error status code refers to a Not Found Error. Maybe the api url that you are trying to access does not match the one inside the routes file whether you are using web.php or api.php.
I suggest using php artisan route:list on the base path of the project to properly see that the route you wanted is registered and match it from there.
It seems to me that PHPUnit can't find not only this URL but the whole website. You could check it by request to "/" in your test.
If I'm right, first of all, I'll suggest checking the param APP_URL in your .env.testing. Usually, I set it as APP_URL=http://localhost, and it works for me.
A 404 code means there was nothing found at the specified route. It could be the route you specified index.php/api/company. Try routing to [host:port]/api/company
Related
I've upgraded from 5.8 to 6 to 7 following the documentation. Now I have a problem where the verification email route returns 404.
I've had a read around and seen a few errors where people have not followed the docs. I have read and implemented the below from the upgrade guide.
"The route path for verifying emails has changed from
/email/verify/{id} to /email/verify/{id}/{hash}."
But there seems to some underlying routing problem. With a little more investigation I've discovered that this works:
Route::get('/email/verify/{id}/{other}', function($id, $other){
dd([$id,$other]);
});
and this does not (the route auth uses but with a closure to test):
Route::get('/email/verify/{id}/{hash}', function($id, $hash){
dd([$id,$hash]);
});
the rest of the web.php routes file is empty.
It would seem using the word hash causes the 404 rather than displaying the array.
When using:
Auth::routes(['verify' => true]);
the route:list command does display the expected route.
Any help greatly appreciated!
I've got laravel set up on a domain on a linux host and I have a WAMP local host set up.
The only route that works is the root, when ever I try go to another route such as domain.com/account I get a "Controller method not found." error.
In my routes.php file I have:
Route::controller('','LoginController');
Route::controller('account', 'AccountController');
In my LoginController, I have just two methods. getIndex and postIndex.
After a couple of hours Googling with no results and playing around with the routes file amongst things, still nothing worked.
I tried adding the below route which didn't work either.
Route::any('hello', function(){
return 'hello!';
});
However, I then commented out my Route::controller('','LoginController'); line and the other routes started working!
I then changed it to Route::controller('login','LoginController'); and this and the other routes still worked. I then changed it to Route::any('','LoginController#getIndex'); and the root and other routes still worked. However, doing it this way, when I cliked the login button on my page nothing happened.
So my question really is, is there something wrong with doing Route::controller('','LoginController');? As everything else seems to 'work'
Laravel save an internal collection of registered routes in the $routes member of the Router class. When dispatching a request, a process of picking each element from this collection and test with current request will be executed to find out which route will be handle. This process is affected by the order of your route registering statements.
When testing each route with the current request, the picked route will be compiled and have a regex pattern. This pattern will be use to check with the current URI by the preg_match function as you can see at this line in Laravel source.
When using Route::controller a special route will be add to your routes collection. If your input is Route::controller($uri, $controller) then this special routes will have a regex pattern as ^/$uri/?P<_missing>(.*)$ and it tells Laravel that this request belong to a missing method of the $controller controller class.
In your case, you have set the value of $uri to an empty string which cause the regex of the special route to be ^/?P<_missing>(.*)$ (setting $uri with the string / cause the same effect). Well, this regex will match every URI. So, the internal route looking up process will abort when look to this special route. This is the reason while the exception has been thrown.
You should not use an empty string or the/ string when register with the Route::controller method like the way you did. Instead, use Route::resource or explicit calls (Route::get, Route::post, ...) to handle your top level routes.
I have not tried that, but maybe you could add a "/":
Route::controller('/','LoginController');
Edit
I was able to reproduce the issue and I solved by changing the order of your route lines:
Route::controller('accounts', 'AccountController');
Route::controller('','LoginController');
I am very confused as to why this is happening but here is the issue guys. Basically I am building an app using laravel4 I want to go to this URL
http://app.tld/books
However I get this error every time:
404: The requested URL /books was not found on this server.
However in my routes.php file I have the route defined:
Route::get('/books', 'BookController#index');
I also have a view and relevent method in Controller:
public function index(){
$books = Book::all();
return View::make('book.index')->with('books', $books);
}
From the comments we gather that it was an Apache issue, not a Laravel issue (mod_rewrite wasn't enabled -- kudos to #watcher), and I'm glad you sorted it out.
For future reference, it seemed likely to be an Apache issue because Laravel throws PHP exceptions on undefined routes, namely a Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException. If you have debug set to true you'll get a neatly styled stack trace with code highlighting and server/request data, if not you'll get a neatly styled "Whoops, looks like something went wrong." message. If, on the other hand, you get a white screen with Times New Roman messages like "404: The requested URL /books was not found on this server.", Laravel isn't even starting up.
As the comments on your question show, there are many other clues which will tell you that it's not your Laravel routes, though from the code you posted and even the title of the question, you seemed to had narrowed it down to routes, which probably had you looking in the wrong place for a while.
I've had this working but now a route is no longer found and I can't see why.
In a javascript function I am making an ajax post to the function with this url:
url: '/customers/storeajax',
In my routes.php file I have the following routes:
Route::post('customers/storeajax', array('as'=>'storeajax', 'uses' => 'CustomersController#storeAjax'));
Route::post('customers/updateajax/{id}', array('as'=>'updateajax','uses' => 'CustomersController#updateAjax'));
Route::resource('customers', 'CustomersController');
Now when I try to POST to the storeajax route I get a ModelNotFoundException which to me means the route could not be found so it defaults to the default customers controller show method - in the error log I can see the following entry:
#1 [internal function]: CustomersController->show('storeajax')
confirming its treating the storeajax as a parameter.
I've placed my additional routes above the default resource route
I've had this working before I can't see where I've gone wrong.
In addition these routes are placed in a group:
Route::group(array('before' => 'sentryAuth'), function () {}
which simply ensures user is logged on. To test though I've removed outside the group and at the top of the file but still they don't work.
The url in my browser is coming up correctly as: http://greenfees.loc/customers/storeajax (which I can see in firebug console
I'm using POST as the ajax method - just to confirm
Can anyone see why this route doesn't work and what I've missed?
Update:
Here's the method inside the controller:
public function storeAjax()
{
$input = Input::all();
$validation = Validator::make($input, Customer::$rules);
if ($validation->passes())
{
$customer = $this->customer->create($input);
return $customer;
}
return Redirect::route('customers.create')->withInput()
->withErrors(validation)
->with('message', 'There were validation errors.');
}
I'm 99% certain though that my route is not reaching this method (i've tested with a vardump inside the method) and the issue relates to my route customer/storeajax cannot be found.
What I think is happening is as customer/storeajax is not found in the list of routes starting with customer it is then defaulting to the resource route that appears on the list and thinks this is a restful request and translating it as customer route which defualts to the show method and using the storeajax as the parameter which then throws the error modelnotfoundexception because it cant find a customer with an id of 'storeajax'
This is evidence by the log detailing a call to the show method as above.
So for some reason my route for '/customers/storeajax' cannot be found even though it appears to be valid and appears before the customers resource. The modelnotfoundexception is a red herring as the cause is because of the routes defaulting to the resource constroller of customers when it cant find a route.
A route not being found raises a NotFoundHttpException.
If you are getting a ModelNotFoundException is because your route is firing and your logic is trying to find a Model, wich it can't somehow, and it is raising a not found error.
Are you using FindOrFail()? This is an example of method that raises this exception. BelongsToMany() is another one that might raise it.
I solved this by renaming the method in the controller to 'newAjax' and also updating the route to:
Route::post('customers/new', array('as'=>'newajax','uses' => 'CustomersController#newAjax'));
the terms store I assume is used by the system (restful?) and creating unexpected behaviour. I tested it in a number of other functions in my controller - adding the term store as a prefix to the method then updating the route and each time it failed.
Something learned.
I added this route to the rules array in the main config.
group/<id:\d+>/<name:\w+>' => 'group/index',
public function actionIndex($id, $name)
{
$this->render('index');
}
When i goto the address /group/1/nameofgroup it works great, but when I try to goto the route /group/1/name-of-group I immediately get the error:
Error 404
The system is unable to find the requested action "1".
Does anyone know how to fix this?
The - in name-of-group is not matched by \w, therefore the request is not directed to this route.
I was able to solve this issue, I wish there was a page that showed how to do routing clearly.
'group/<id:\d+>/<name:[\w-]+>' => 'group/index',
was the correct pattern.