4

So I'm trying to test my Laravel’s middleware which will return redirection.

If the request does not satisfy the middleware’s requirements, the request will be redirected using redirect()->route('name')

I tried getting the return value from the middleware so

$response = $middleware->handle($request, function ($req) { return $req; }, 'server:summary:view:edit'); \Log::info($response); 

the $response is an instance of Illuminate\Http\RedirectResponse. When I do \Log::info($response); I get this result.

HTTP/1.0 302 Found Cache-Control: no-cache, private Date: Mon, 13 Jul 2020 08:12:27 GMT Location: https://myrandomurl.test/name <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="refresh" content="0;url='https://myrandomurl.test/name" /> <title>Redirecting to https://myrandomurl.test/name</title> </head> <body> Redirecting to <a href="https://myrandomurl.test/name">https://myrandomurl.test/named</a>. </body> </html> 

So how do I get the URL from the Location tag ? or How do I get the redirect URL from Laravel redirectResponse?

I tried browsing the doc at https://laravel.com/api/5.8/Illuminate/Http/RedirectResponse.html#method_content but there's no method that shows redirect route.

I need the route to assert it for the successful test result.

4
  • Location is a header so, how about $response->header('Location') ? Commented Jul 13, 2020 at 8:26
  • 1
    @apokryfos didn't work. header() method on redirectResponse is used to set the request header. not get. Commented Jul 13, 2020 at 8:29
  • 2
    Possibly $response->headers->get('Location') might work in that case, however if this is a test there are assertions that can do this as well like assertRedirect Commented Jul 13, 2020 at 8:33
  • 2
    @apokryfos Can't use $response->headers->get('Location') since redirectResponse didn't have headers properties. But Oh shit you right about the assertRedirect(). I should've used that. I probably should delete this question then. Commented Jul 13, 2020 at 8:50

1 Answer 1

7

The Illuminate\Http\RedirectResponse inherits Symfony\Component\HttpFoundation\RedirectResponse class that has getTargetUrl method:

$response->getTargetUrl(); 

Instead you may use assertRedirect for testing purposes.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.