dimanche 31 mars 2019

Get rid of all redirects and "non-api" behaviour in laravel 5.8

I'm working with laravel for a long time now, but I'm currently facing some issues when using laravel as API-only Backend.

I want to develop the frontend seperatly and therefore treat laravle as API only. As most of things work very easily I have huge issues when writing tests.

I'm still using web middleware group (not api) and when using the auth middleware everything works when testing with postman for example, but when writing a test.

Here's a simple example:

/** @test */
public function search_competitions_unauthorized ()
{
    $response = $this->get('/competitions/ABCDEFG');

    $response->assertStatus(401);
}

Then endpoint /competitions/ABCDEFG is protected by the auth middleware.

I receive a 500 as response code because there is no route with the name login defined. This is easy to solve ofcourse (create route with name login), but I want that laravel treats every request as "api" request that does not want any redirects.

I've tried a few things in order to get rid of this behaviour:

I've defined a new class "DefaultRequest" that extends Illuminate\Http\Request

class DefaultRequest extends Request
{
  public function expectsJson()
  {
    return true;
  }

  public function wantsJson()
  {
    return true;
  }
}

And changed the index.php in the public folder to

$response = $kernel->handle(
    $request = App\Http\Requests\DefaultRequest::capture()
);

Also all the requests used in my controllers use this as their default

As I had the same issue with request validation, I've also added this method to my default request:

protected function failedValidation(Validator $validator)
{
    throw new HttpResponseException(response()->json($validator->errors(), 422));
}

I have the feeling that this should be easier to resolve. It seems like in general this would only be a problem for me while testing and I could set specific headers in my tests. But I actually want to disable all these redirect behaviours as I NEVER want these for the project.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2TQwpJu
via IFTTT

Aucun commentaire:

Enregistrer un commentaire