I am defining the routes in the file routes/web.php
(I use laravel 5.7).
Normally, I define them like this:
Route::get('url_para_mostrar', Controlador@metodo)->name('nombre_de_ruta');
The problem is that I have multiple routes to methods that should not return a view. They are methods that are called by ajax, to return a response with some data that is placed in the current view. I started by defining the routes like this:
Route::get(null, Controlador@metodo)->name('nombre_de_ruta');
In the first parameter I put null
, because since they are not going to give rise to a view, it is not necessary that there be a URL to show. The problem is that when I have more than one route like this, the router doesn't recognize the name I put in the method name()
, and it throws me an exception, saying that the route doesn't exist.
So the question is this: when there are routes that point to methods that don't return a view, what is the proper way to define them? I could pad the first parameter with anything since the URL will never be displayed, but it sounds like a hack to me. I'm sure there is a better way to define those routes. I don't know if I should define them with a specific syntax in api.php
and, if so, how to call them correctly. Can you explain me the correct way to do it, laravel style? Thank you very much.
Regarding Shaz's comments, I call them with a jquery ajax, like this:
var url = "{{ route('nombre_de_ruta') }}";
$.ajax({
url: url,
type: 'post',
data: {
pasajero: $('#pasajeros').val(),
ciudades: $('#ciudades_disponibles').val(),
_token: "{{ csrf_token() }}",
},
success:function(resultado) {
console.log (resultado);
}
});
I don't know if you mean this. It is the call that I have in a view.
To define routes for AJAX calls, you have to define them in the
routes/api.php
. Putting NULL in the first parameter of the route is not to not return views, the first parameter is the address of the route, what you return depends on what you do in the method.If you want to define an API route, it's business as usual
Route::get('prueba', 'Controlador@metodo')
. Then you will be able to access that route as follows: "my-domain.com/api/test".When using api routes, Laravel by default assumes that you will return json responses. Still, if you need to return something other than a view, just in the method you call, change
return view(vista)
toreturn response()->json()
to return data in json.