Laravel Feature test can't make a DELETE request - laravel

I'm using Laravel 5.4
web.php
Route::delete('claim/{id?}', 'ClaimController#claimRemove');
myTest.php
$response = $this->json('delete', 'claim', [
'id' => $id
]);
When i run phpunit, i'm getting the
MethodNotAllowedHttpException
BUT if I run it via Postman or phpstorm rest client - it works fine, so the reason is somewhere in $this->json method. I also tried $this->call.
If I switch delete method to post in web.php and in my test file - test is passing well.
So, question is - why it's not working with DELETE method or how to test DELETE calls?:)
Thanks.

Seems like it was version issue. Didn't modify anything, but after two weeks just composer update and test passed fine.

If composer update simply solved your problem it sounds like that your route cache has not been updated with your latest route changes. Both composer update and composer install include normally a list of artisan commands such as route:clear as they are specified indirectly in the composer.json file when optimize is used.
Secondly, use this form below due to the fact the id is part of your route otherwise it will hit the route without an id. However it will also be acceptable because you have made the parameter optional.
$response = $this->json('delete', 'claim/' . $id, []);

The way you have defined your routes, the ID needs to be passed in the URL.
Replace
$response = $this->json('delete', 'claim', [
'id' => $id
]);
with
$response = $this->json('delete', 'claim/' . $id, []);

Related

Merging laravel dingo with laravel-modules and caching config

Here is the problem.
I started a dingo project and am using laravel-modules in it. Every module has its own routing files. Using the project in development environment, everything works fine.
But when I run php artisan config:cache, when a request comes to laravel, it return the response The version given was unknown or has no registered routes. As I see, the problem is dingo just check the default api.php and web.php files to find the route. But module routes are not stored in that files. I store them in Modules/module_name/route/api.php file (as laravel-modules suggested).
Any suggestion would be welcome.
change api file of module with version param in group session like this:
$api = app('Dingo\Api\Routing\Router');
$api->group(['version' => 'v1'], function ($api) {
...
});

Laravel 6 with laravel passport, weird Guzzle error

I have followed the instructions for installing a password client for Laravel passport exactly as written in the Laravel docs and with default Laravel 6.0 composer versions of guzzle, etc. I have done the install on an existing project and as a clean install, both on local dev environment and live server, and every time I try to post to the example.com/oauth/token route, I am greeted with a crazy Guzzle error that seems to have no previous search history on the internet. The error is (summarized):
GuzzleHttp\Exception\ServerException
/var/task/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113
"Return value of Zend\\Diactoros\\normalizeServer() must be of the type array, none returned"
I am running php 7.3 in all environments, but tried php 7.2 and 7.1 and got the same result. I'm running Laravel Valet locally, and have never seen anything like this on any other project. I am also running a staging server with Laravel Vapor, and I get the exact same error. My guzzle request is almost exactly the same as Taylor Otwell's example in the Laravel docs, and looks like this:
$http = new \GuzzleHttp\Client;
$response = $http->post(env('API_TOKEN_URL'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => env('PASSPORT_CLIENT_ID'),
'client_secret' => env('PASSPORT_CLIENT_SECRET'),
'username' => $request['username'],
'password' => $request['password'],
],
]);
return json_decode((string) $response->getBody(), true);
I have data dumped all variables to verify that the username, password, client_id and client_secret are all accurate. It doesn't seem to be an authentication issue at all, but some issue with Guzzle passing proper server headers. I have no idea how to fix, as there is no previous record of this issue that I could find anywhere else on the internet. Any ideas???
if someone face this issue just update the package name: laminas/laminas-diactoros to latest version such as 2.2.2 by running
composer require laminas/laminas-diactoros
the problem comes from
normalize_server.legacy.php
its does not return anything.

Check Laravel 5.7 login from external script

I have a Laravel app and I need to check if a user is logged and who from a external script. I'm using the following lines to load Laravel and try to check it.
require_once __DIR__.'/../../../vendor/autoload.php';
$app = require_once __DIR__.'/../../../bootstrap/app.php';
$app->make('Illuminate\Contracts\Http\Kernel')
->handle(Illuminate\Http\Request::capture());
/*if (Cookie::get(config('session.cookie')) != "") {
$id = Cookie::get(config('session.cookie'));
Session::driver()->setId($pericod);
Session::driver()->start();
}*/
$isAuthorized = Auth::check();
if(!$isAuthorized){
echo "NO AUTORIZADO";
exit();
}
With this lines I can access any Laravel function and I can check the login if I made GET request to the external scripts, but when the request is POST it always fails. I'm unable to check the login and I see that the session changes because can't get the existing session.
I have made many tests and I think that somethings of Laravel are not working fine, like routes or middlewares. I can made it work if I disable all encryption of the cookies and the session, but I want to use this security functions.
I'm using updated Laravel 5.7 and I had this code working in Laravel 5.4
Thank you for your help.
I discovered the problem,
The trick is that the route is external to laravel so laravel's route resolver identifies the current route as /.
It was working on GET requests because in my routes file I have the / route only as get. If I set the / route as any, everything works.
I wasn't seeing the problem because I was not terminating Laravel's execution. If I change the logged user verification to this, it shows the error:
$isAuthorized = Auth::check();
if(!$isAuthorized){
echo "NO AUTORIZADO";
$response->send();
$kernel->terminate($request, $response);
exit();
}
This two lines ends laravel execution and returns the error "405 Method Not Allowed".
$response->send();
$kernel->terminate($request, $response);
Thank you for your help.

Laravel 5.5 Route groups

I was having this in my website using Laravel 5.3 :
Route::group(['namespace' => 'Admin', 'prefix' => 'admin', 'middleware'=>'auth'], function(){
Route::resource('posts', 'PostsController');
});
This lets me go to the admin panel using: mywebsite/public/admin/posts.
Now, when I migrated the site to Laravel5.5 I got this error Route[admin.posts.create] not defined when i attempt to open the link Create post which was working fine before.
I know that routing system has changed but I did not know how to have such links in new Laravel5.5. I tried url instead of route but I got the same error. I also checked the new documentation but I did not get exactly how to have the same link system.
Can anyone have a better explanation of this new routing system? (I have to migrate the site to 5.5).
Laravel names resource routes by default, you can check them by running php artisan route:list
If you want to override them for any reason you can pass in an array when you define the route and override each individual route name like so:
Route::resource('posts', 'PostsController', ['names' => [
'create' => 'admin.posts.build'
]]);

Why is my CSRF token empty when using Form::open()?

I am just starting out so please forgive me. I have a solid grasp on CodeIgniter, so I understand what is going on. However, I am noticing that my CSRF token is empty when I am creating a form. I am working through the laracasts videos to get a gasp on Laravel workflow.
myfile.blade.php
{!! Form::open((array('action' => 'MyController#method'))) !!}
...
{{!! Form::close() !!}}
Here is what I am getting when I view the source:
<form method="POST" action="http://mysite.dev/route" accept-charset="UTF-8">
<input name="_token" type="hidden">
</form>
I've looked through the config directory, but see nothing on having to enable csrf. Is there an additional setting somewhere I need to update?
Thank you for your suggestions.
EDIT
Even this gives me an empty hidden input field:
{{ Form::token() }} // <input name="_token" type="hidden">
EDIT
Here is what my controller looks like:
//use Illuminate\Http\Request;
use Request;
use App\Article;
use App\Http\Requests;
use App\Http\Controllers\Controller;
public function store(Request $request)
{
$input = Request::all();
return $input;
}
So my updated form tag looks like this:
{!! Form::open((array('action' => 'ArticleController#store'))) !!}
...
When I submit, I can see the json response - the token is obviously empty.
{"_token":"","title":"test","body":"test"}
The Laravel Fundamental series is for Laravel 5.0 so you have a few options. You can install Laravel 5.0 to continue with that series. In order to install L5.0, you need to run this command:
composer create-project laravel/laravel {directory} "~5.0.0" --prefer-dist
If you want to use Laravel 5.2 though (which I would recommend and Jeffrey Way will most likely release a series on this soon), there are several extra things to take into consideration.
First, put all your routes inside a "web" middleware group like this:
Route::group(['middleware' => ['web']], function () {
// Put your routes inside here
});
In the past, there were several middlewares that ran on every request by default. In 5.2, this is no longer the case. For example, the token is stored in the session, but in 5.2, things like the "StartSession" middleware are not automatically applied. As a result, the "web" middleware need to be applied to your routes. The reason for this change in 5.2:
Middleware groups allow you to group several route middleware under a single, convenient key, allowing you to assign several middleware to a route at once. For example, this can be useful when building a web UI and an API within the same application. You may group the session and CSRF routes into a web group, and perhaps the rate limiter in the api group.
Also, in the Laravel Fundamental series, Jeffrey pulls in the "illuminate/html" package, but now, most people use the laravel collective package. They handle a lot of the Laravel packages that are taken out of the core. As a result, I would remove the "illuminate/html" package. In your composer.json file, remove "illuminate/html: 5.0" (or whatever is in the require section). Also, remove the corresponding service provider and form facades that you added to your config/app.php file.
To install the laravel collective version, add this in your composer.json file instead: "laravelcollective/html": "5.2.*-dev". Then, run composer update. Once that's done, in your config/app.php file, add this to your providers array:
Collective\Html\HtmlServiceProvider::class,
and add this to your aliases array:
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
I hope I'm not missing anything else.
This is a config issue .You need to set the app key in your config file ...config/app.php to a 32 character string or use artisan cli php artisan key:generate to genearte the key for you to be able to use the CSRF token .
Also make sure that you include routes that use the CSRF token in the web group route .
You may exclude URIs by defining their routes outside of the web middleware group that is included in the default routes.php file, or by adding the URIs to the $except property of the VerifyCsrfToken middleware: http://laravel.com/docs/5.2/routing#csrf-protection
If you have a login page and you want to clear out the session using:
Session::flush();
Don't forget that this also cleans out the csrf token before it can be put in the view
It should be
{!! Form::open((array('action' => 'MyController#method'))) !!}
...
{!! Form::close() !!}
I have solved the issue of HtmlService provider actually 5.2 version removed Illuminate and add collective follow the step to solve the issue:
composer require laravelcollective/html
composer update
add in config/app.php
'providers' => ['Collective\Html\HtmlServiceProvider'],
'aliases' => [
'Form' => 'Collective\Html\FormFacade',
'Html' => 'Collective\Html\HtmlFacade',
],
Then you are able to use that form.

Resources