How to return parameter route from Laravel to Ajax

Viewed 55

I am trying to return the parameter of a laravel route to an ajax response. This is my

public function getPermissions(Request $request)
{
        //$v = request()->route()->parameters('profile');
        $v = request()->route()->parameters();
        return var_dump($v);
}

JS:

function getPermissions() {
    let data_permissions = '';
    $.post({
        url: '/permisos',
        async: false,
        success: (res) => {
            console.log(res)
        }
});
}

This is my route:

http://base-laravel.test/profiles/1/edit

In the console returns an empty array. I intend to obtain the 1 that they see on the route. Suggestions?

2 Answers

You have not added the data to send from Laravel to Ajax Controller. You can pass the data inside the object of the data like

$.post({
    url: '/permisos',
    type: "POST",
    data: {
        id: '{{$user->id}}' // Suppose you need to pass the user id to the controller
    },
    async: false,
    success: (res) => {
        console.log(res)
    }
});

When retrieving the id in the AjaxController, you can simply use the Request $request variable.

public function getPermissions(Request $request)
{
    //dd($request->all())
    //dd can be use to die and dump the all variable values 
    return $request->id;
}

Viewing in the console, it will display the Ajax Request Id.

You can use this way

$data = $this->route('parameter_to_access');
return $data
Related