Laravel resource controller ajax call
Run this from your command line, it will list all URL routes coupled together with the controller methods they are attached to:
$ php artisan routes # Laravel 4
$ php artisan route:list # Laravel 5
Making a resource controller as you are creates 7 different routes. None of those routes include store
anywhere in the URL. The store
method exists on the controller, but responds to POST requests to the URL /faq
(in your example)
The solution to this problem
Change your jQuery to POST instead of GET your data (which is default), and change your AJAX url to '/faq'
. It should then hit the correct route at that point.
As far as being able to hit a resource controller route without knowledge of the actual route, that on its face is impossible (think about trying to visit google.com without knowing that google.com exists). I think however I understand what you're trying to do. I'm assuming that the AJAX request is being sent off as a response to some user action, such as the clicking of a button. You can attach a data attribute to that button with the value you're wanting so that you can make these requests in a sort-of resource agnostic way.
Something like this:
<button class="test" data-resource="faq">Click me!</button>
$('.test').on('click', function(e) {
var resource = $(this).data("resource");
$.ajax({
url: '/' + resource,
dataType:'json',
type: 'post',
success:function(data){
console.log(data);
}
});
});
flyingL123
Updated on June 04, 2022Comments
-
flyingL123 over 1 year
Using Laravel 4.2, I have a resource controller setup like this:
Route::resource('faq', 'ProductFaqController');
When I hit the
/faq
URL on my server, the controller'sindex()
method correctly loads.In a js file, I would like to make an ajax call to one of the other actions for this resource controller, for example, the
store
action. Therefore, I do something like this:$.ajax({ url:'store', dataType:'json', success:function(data){ console.log(data); } });
The problem I'm having is that since the URL is
/faq
(without a trailing slash), the ajax call gets made to/store
, instead of/faq/store
.Am I missing something here or do I need to prefix the url for all of my ajax calls with the route?
If I do need to add some sort of prefix, how do I get the appropriate prefix to use no matter resource controller is being called?
-
dabadaba over 9 yearsexactly, since Laravel provides you with RESTful routing when declaring routes with
Route::resources()
thestore()
action is executed with a POST to your resource's name (faq
) -
rhand over 6 yearsI think it should be
php artisan route:list
notphp artisan routes
-
Jeff Lambert over 6 years@rhand In Laravel 4 it was
php artisan routes
It looks like some of the Laravel 4 documentation has started to go missing (or it was never there), but I found a source. I went ahead and added that to the answer though, thanks for pointing it out.