Generate route url in controller


#1

Hello,

I want to return a Location header for my response and I would like to be able to use a helper or something.

I saw in adonis docs that there is route() helper for view, I tried to use this in my controller, but it’s not working.

There is something else I could use or I should just use strings?


#2

Hey @melokki! :wave:

Here you go: https://adonisjs.com/docs/4.1/response#_redirect


#3

thank you for your replay @romain.lanz but this is not what I am looking for.
I have the following code:

return response.header('Location', '')
                        .json({
                          status: 'warning',
                          message: 'This role already exists.',
                          data: role
                        })

and in that location header I want to send the route where the resource can be found.

I tried something like this, but It’s not working

return response.header('Location', route('roles.show', role))
                        .json({
                          status: 'warning',
                          message: 'This role already exists.',
                          data: role
                        })

and I am not getting any errors, but as soon as I remove the route('roles.show', role) code everything is working again.


#4

You go an error because the route helper doesn’t exist.

Could you please add more context to your request? It seems very weird to add the Location header to a response that send JSON.


#5

I was thinking that when I try to store a new resource first I will search for it’s name, if the resource exists, I will return a warning and a Location header so the user knows where to find that resource.


#6

Well, that’s not how it works.
The Location header is used to tell the browser where to redirect the user.

Read more about it here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location


#7

I understand.
Thank you very much @romain.lanz