How to setup url in JavaScript to pass multiple parameter to controller in Laravel without using request - laravel

I setup the url by JavaScript to call a function in controller with only one parameter($RoleID) like this
$(document).on('change','#role',function(){
$RoleID = $(this).val();
let $url = '{{route("Admin.role.permission.LoadMember",':id')}}'
$url = $url.replace(':id', $RoleID);
$.ajax({
url:$url,
success:function(data)
{
$('#member').append(data);
}// end fucntion success
});
});
It works ok, Now I would like to do the same with more than one parameter without using Request
I tried like this
document.getElementById('function').addEventListener('change', function(e) {
if (e.target.name==='function') {
$FncID = e.target.value;
let $url = '{{route("Admin.role.permission.LoadActionsInRolePermissions",'[$ModuleID,$RolID,$FncID]')}}';
$.ajax({
url:$url,
success:function(data)
{
$('tbody').html(data);
//$('#member').append(data);
}// end fucntion success
});
}
})
But unfortunately, It is not work. Pls help me.
Thank in advance

You haven't shown us how you defined the route, nor what laravel version you're using, but I highly suggest taking a read on the docs on how route parameters work.
As example, say this is your LoadMember route:
Route::get('permission/load-member/{id}', [PermissionController::class, 'loadMember'])->name('Admin.role.permission.LoadMember')
Then, as follows:
{{route("Admin.role.permission.LoadMember",['id' => ':id'])}}.
By passing an associative array with key => value assignment, Laravel knows where to place the given values in the url.
For a multi-parameter route, it works exactly the same:
Route::get('permission/load-actions-in-role-permissions/{moduleId}/{rolId}/{fncId}', [PermissionController::class, 'loadActionsInRolePermissions']) ->name('Admin.role.permission.LoadActionsInRolePermissions')
{{route("Admin.role.permission.LoadActionsInRolePermissions",'['moduleId' => $ModuleID, 'rolId' => $RolID, 'fncId' => $FncID]')}}
Also, may I suggest using camelCase for variable names, and kebab-case or snake_case for route naming? It highly improves readability and future developers who might work on your project will have a better guess at how your route structure works.

Related

error 404 while using {{url()}} on laravel ajax

Greating,
I have some error while using ajax on laravel, the console return 404,
that's my ajax
$('#btn_search_postcode').click(function(e){
let postcode = $('#postcode').val();
if(postcode != ""){
$.ajax({
method: "GET",
url: "{{route('company.postcode')}}",
dataType: "JSON",
data:{
'id':postcode
},
success: function(result){
if(result != ""){
console.log(result.prefectureid);
}
else{
console.log('null');
}
}
})
}
})
I have change the url to "{{url('company/postcode')}}/"+postcode but still error
that's my route
Route::GET('/company/postcode/{id}', 'mycontroller\companyController#getPostCode')->name('company.postcode');
but the code working fine when I change the url into
url: "http://localhost/mylaravel/public/company/postcode/"+postcode,
I can't use the last method because in other pc using different port.
can anybody help me for this issue?
note : i can see the csrf token, when i add the csrf token again in ajax, I see 2 token on error link
EDIT:
I still not resolve that, but now im using url:rootUrl+"/companies/postcode/"+postcode, to resolve that issue, is it ok to do like that?
The problem is that your route has a required parameter {id} and since you don't provide it when you render the url of the route, laravel doesn't find the route.
Two solutions:
make the id parameter optional in your route declaration like so Route::GET('/company/postcode/{id?}', 'mycontroller\companyController#getPostCode')->name('company.postcode'); (note the {id?})
provide the parameters trough php with some defined variable in the view ex: {{route('company.postcode',$id)}}
Cordially
you have to change it like these
url: "{{url('company/postcode')}}"+'/'+postcode
please try these and let me know what happened
If I understand what you are asking, you have a route that is named company.postcode, is that correct? If you do have that route, and now what you are wanting is to get the company by postcode, you will need to take advantage of Laravel's Route Model Binding. What you can do is go into your model and create a function like this:
public function getRouteKeyName()
{
return 'postcode';
}
Yet, I see an issue with that that can cause you some issues down the road. What happens when you have multiple companies with the same postcode? How will Laravel know which one you want?
A much better option is going to be to use the id field and retrieve your company with it. Unless you make the postalcode field in the database a unique field. Which again raises the question of what happens when you have two or more companies wanting access to your website that share the same postal code?

Laravel routing with or without parameter in a group

For my application I am trying to create a few routes entries.
One entry to initialise the application and another for AJAX requests.
So my application should hit the initialise function if I type https.test.com/app/drive but also if I want to type some additional parameters at the end something like this: https:test.com/app/drive/specificTabA or https:test.com/app/drive/specificTabB
The problem is that when ever I type https.test.com/drive/specificTabNameA this clashes with the fetchData get route used by my AJAX call.
How can I access the initialise function when hitting this URl https.test.com/app/drive or also hitting something like this: https:test.com/app/drive/specificTabA or https:test.com/app/drive/specificTabB?
Route::group(['prefix' => 'drive'], function () {
Route::get('', 'CustomController#initialise');
Route::get('fetchData', 'CustomController#fetchData');
});
I've done some tests, and came with the following conclusion/solution:
Route::group(['prefix' => 'drive'], function () {
Route::get('fetchData', 'CustomController#fetchData');
Route::get('{param?}', 'CustomController#initialise');
});
CustomerController:
function initialise($param = null)
{
...
}
Note that by changing the order of the routes you will actually load the correct route.
When you visit /drive/fetchData it will load fetchData route
When you visit /drive/ it will load initialise route without arguments
When you visit /drive/xyz it will load initialise route with $param being xyz
Hope it helps :)
My friend I want to get your attention to Laravel docs https://laravel.com/docs/5.0/routing#route-parameters especially this one Route Parameters. You can tell router that this route can have parameter but also can not have it. Look at this example
Route::get('/{specific?}')
Now you can get this specific parameter in your Controller function after request
public function initialize (Request $request, $specific = null)
Set it default to null as this param can both be past and not, so it should have some default value.
Good luck ;)
The following should work for you:
Route::group(['prefix' => 'drive'], function () {
Route::get('fetchData', 'CustomController#fetchData');
Route::get('{path?}', 'CustomController#initialise')->where(['path' => '.*']);
});
This will allow the following path:
/drive => initialise
/drive/1 => initalize
/drive/1/2/3 => initalize
/drive/fetchData => fetchData
Adding ->where(['path' => '.*']) will route any path to initalize, e.g. /1, /1/2, /1/2/3.
If you only want to allow the path to be one level deep you can remove the where:
Route::get('{path?}', 'CustomController#initialise');

Laravel & Ajax return array response no parsing

Currently I'm trying to pull some data via ajax and I'm not getting the data to appear properly.
In my ajax call I have this:
$.ajax({
url:"{{ route('pricing.fetch') }}",
method:"POST",
data:{select:select, value:value, _token:_token, dependent:dependent, productId:productId},
success:function(result)
{
$("ul[data-dependent='quantity']").html(result);
This works as expected. The problem is I'm trying to return data from different tables in my db. So I'm trying to do it by changing my result in ajax to this.
$("ul[data-dependent='quantity']").html(result.productQuantities);
The reason for me wanting to do this is because I have multiple drop downs I need. So I would also like to do another one like this:
$("ul[data-dependent='quantity']").html(result.productPaperStock);
my controller code is like this:
$data = Product::with(['productQuantity', 'productPaperstock'])->where('ID', $productId)->first();
// pull the quantity for this product
$productQuanties = $data->productQuantity;
$productPaperStock = 'hello';
$output = '';
foreach($productQuanties as $productQuantity)
{
$output .= "<li><span>" . $productQuantity->quantity_name . "</span></li>";
}
return response()->json["productQuanties" => $productQuanties, "productPaperStock" => $productPaperStock]);
I'm not sure what I'm doing wrong but using this example above I get a 500 error.
You need to set dataType: json option in your ajax request, and then in your controller, you can return json response.
Also, you are missing the starting brace in your controller code. The correct code is
return response()->json(["productQuanties" => $productQuanties, "productPaperStock" => $productPaperStock])
(Note that ...storage/logs/laravel.log is an awesome place to get insights into what's screwing your app:))

how to use Route::input in laravel4?

I am trying to use Laravel 4 method called Route:input("users"). But I am getting following error
Call to undefined method Illuminate\Routing\Router::input()
Any idea how Route::input() works. Is there any file I need to change.
Thanks all
Route::filter('userFilter', function () {
if (Route::input('name') == 'John') {
return 'Welcome John.';
}
});
Route::get('user/{name}', array(
'before' => 'userFilter',
function ($name) {
return 'Hello, you are not John.';
}));
It looks as though Route::input was added in Laravel 4.1, make sure this is the version you are working with if you need to use this functionality.
I assume you've read the docs, but since you asked how it works, here's the example:
Accessing A Route Parameter Value
If you need to access a route parameter value outside of a route, you may use the Route::input method:
Route::filter('foo', function()
{
// Do something with Route::input('users');
});

Call a controller in Laravel 4

In Laravel 3, you could call a controller using the Controller::call method, like so:
Controller::call('api.items#index', $params);
I looked through the Controller class in L4 and found this method which seems to replace the older method: callAction(). Though it isn't a static method and I couldn't get it to work. Probably not the right way to do it?
How can I do this in Laravel 4?
You may use IoC.
Try this:
App::make($controller)->{$action}();
Eg:
App::make('HomeController')->getIndex();
and you may also give params:
App::make('HomeController')->getIndex($params);
If I understand right, you are trying to build an API-centric application and want to access the API internally in your web application to avoid making an additional HTTP request (e.g. with cURL). Is that correct?
You could do the following:
$request = Request::create('api/items', 'GET', $params);
return Route::dispatch($request)->getContent();
Notice that, instead of specifying the controller#method destination, you'll need to use the uri route that you'd normally use to access the API externally.
Even better, you can now specify the HTTP verb the request should respond to.
Like Neto said you can user:
App::make('HomeController')->getIndex($params);
But to send for instance a POST with extra data you could use "merge" method before:
$input = array('extra_field1' => 'value1', 'extra_field2' => 'value2');
Input::merge($input);
return App:make('HomeController')->someMethodInController();
It works for me!
bye
This is not the best way, but you can create a function to do that:
function call($controller, $action, $parameters = array())
{
$app = app();
$controller = $app->make($controller);
return $controller->callAction($app, $app['router'], $action, $parameters);
}
Route::get('/test', function($var = null) use ($params)
{
return call('TestController', 'index', array($params));
});
Laurent's solution works (though you need a leading / and the $params you pass to Request::create are GET params, and not those handled by Laravel (gotta put them after api/items/ in the example).
I can't believe there isn't an easier way to do this though (not that it's hard, but it looks kinda hackish to me). Basically, Laravel 4 doesn't provide an easy way to map a route to a controller using a callback function? Seriously? This is the most common thing in the world...
I had to do this on one of my projects:
Route::controller('players', 'PlayerController');
Route::get('player/{id}{rest?}', function($id)
{
$request = Request::create('/players/view/' . $id, 'GET');
return Route::dispatch($request)->getContent();
})
->where('id', '\d+');
Hope I'm missing something obvious.
$request = Request::create('common_slider', 'GET', $parameters);
return Controller::getRouter()->dispatch($request)->getContent();
For laravel 5.1
It's an Old question. But maybe is usefull. Is there another way.
In your controller: You can declare the function as public static
public static function functioNAME(params)
{
....
}
And then in the Routes file or in the View:
ControllerClassName::functionNAME(params);

Resources