I want to make one route for all my ajax requests in laravel. Currently what I have is:
Route::post('/ajax/{method}', 'AjaxController@index')->name('ajax-request');
Can I do something like this (using dynamic method name):
Route::post('/ajax/{method}', 'AjaxController@{method}')->name('ajax-request');
so for example when I call /ajax/get_comments
, it will call AjaxController@get_comments
method ?
You can add closure function to your route to achieve this one.
Route::get('ajax/{method}', function($method){
$app = app();
$controller = $app->make('App\Http\Controllers\AjaxController');
return $controller->callAction($method, $parameters = array());
});
Now, call the get_comments
method like:
localhost:8000/ajax/get_comments
NOTE: make sure your controller is inside app/Http/Controller/
directory.
I hope you understand
The Route methods( get
, post
etc) can accept their's second parameter as string using the following pattern ControllerName@methodName
.
You could retrieve the {method}
parameter from request path and append it to Route method's second parameter. ie, like 'ControllerName@'. 'methodName'
'ControllerName@'. 'methodName'
Try the following :
Assuming {method}
would be your second segment in the request path. [If not change the value in the segment()
parameter.]
Try the following:
Route::post('/ajax/{method}', 'AjaxController@'.(Request::segment('2')))->name('ajax-request');
Please Note :
If you choose to put URL parameter to be used as the method name there are some chance that, if a user is able to change the request path other than the specified one, run time exceptions will be thrown.
Consider the following scenario :
Your AjaxController
has only methods get_comments()
and get_deleted_comments()
.
If the request is /ajax/get_comments
or /ajax/get_deleted_comments
then their corresponding methods will work. But if request is something like /ajax/get_xyz
and you dont have a method named get_xyz
in your AjaxController
then a BadMethodCallException
will be thrown.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.