jim1506's avatar

Using Named Route with parameters in a javascript call

I have a route in my web.php file:

Route::get('noBodyDetail/{id}','VehiclesController@noBodyDetail')->name('noBodyDetail');

and in a datatables I am trying to establish a link using a javascript call:

<a href="#" onclick="showDetail({{ $im->id }})">@fa('eye')</a>

All OK so far.

My problem is calling the named route in a javascript function.

I have tried

function showDetail(id)

{ var url = "{{ route('noBodyDetail') }}/" + id;

$( "#detail" ).empty();

$( "#detail" ).load( url ); }

But I am getting a missing parameter error

Missing required parameters for [Route: noBodyDetail] [URI: admin/noBodyDetail/{id}].

Can someone point out to me how to call a named route and passing a parameter in a javascript function?

Thanks!

0 likes
11 replies
crnkovic's avatar

There is a library called ziggy that allows you to use route helper in JS for named routes. I've been using it a lot lately and it works wonderfully: https://github.com/tightenco/ziggy

I believe there is no better (not hacky) solution to your problem.

jim1506's avatar

Ziggy is for 5.6, but because of my client I am forced to use 5.5

crnkovic's avatar

I'm not sure, even the installation docs say:

(if Laravel 5.4) Add Tightenco\Ziggy\ZiggyServiceProvider::class to the providers array in your config/app.php.

minjon's avatar

@jim1506 Named route noBodyDetail includes parameter $id. So you have two options here:

To pass $id to the page and call the route by the name:

var myUrl = "{{route('noBodyDetail', $id)}}";

To call the url address:

var myUrl = '/noBodyDetail/' + myId;
jim1506's avatar

Composer gives an error saying 5.6 is needed and I cannot find an alternative installation on the github site

jim1506's avatar

I have changed to var url = '/noBodyDetail/' + id; but I am getting a 404 when I examine with developer Tools, although the named route is definitely there.

lemaur's avatar

You can output a list of your routes with artisan, using this commend $ php artisan route:list, so you can check if the route you try to call exists or is misspelled. It's just like double check.

lemaur's avatar

I think you have to write:

var myUrl = '/admin/noBodyDetail/' + myId;

As per your snippet:

Missing required parameters for [Route: noBodyDetail] [URI: admin/noBodyDetail/{id}].
minjon's avatar

@jim1506 will you please go to your route list - php artisan route:list - and copy the url address for the route 'noBodyDetail'. Then, hit your url and check whether it matches with the first one.

Please or to participate in this conversation.