Drwhite
Drwhite

Reputation: 1695

How to Call Laravel Route From js File

i'm making an ajax call from my laravel blade view like this:

function deleteUser(user_id)
{
    $.ajax({
        url: '{!! route('users.delete', ['id' => user_id]) !!}',
        type: 'DELETE',
        data: {_token: '{!! csrf_token() !!}'},
        dataType: 'JSON',
        success: function (data) {
            console.log(data);
        }
    });
}

and in my routes.php file i defined the route:

//routes.php
Route::delete('users/{id}/delete', 'UserController@delete')->name('users.delete');

where i'm just refreshing the page an error was occured:

Use of undefined constant user_id- assumed 'user_id'

i realized that the user_id parameter is injected by the wrong way inside the route() method within javascript block.

is there a way to inject parameters in the url of ajax call inside the route method of laravel?

Upvotes: 2

Views: 5149

Answers (2)

max234435
max234435

Reputation: 567

You can trying doing it this way '{{url("users/$user->id/delete")}}'; your route will pick it up and redirect where it needs to go

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163798

You can't use Laravel helpers in your JS, unless your JS code building dynamically (which is bad idea). So just use manually built URLs.

url: 'users/145/delete',

Upvotes: 0

Related Questions