Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop php script in Laravel when Axios request is cancelled?

Tags:

php

laravel

axios

I'm making a live search using Laravel, VueJs and axios, so every time the user types a new word, the previous request will be cancelled. My problem is that even when I cancel the previous request using the cancel token (https://github.com/axios/axios#cancellation), the php script is still running.

QUESTION: How can i stop the php script if the axios request has been cancelled?

my Vuejs code

fetchData(query) {
    if(cancel != undefined)
        cancel();   // cancel the previous request
    axios.get("http://sample-link", {
            cancelToken: new CancelToken(function executor(c) {
                cancel = c;
            }),
            params: {
                query : query
            }
    }).then(response => {
        console.log(response);  
    }).catch(error => {console.log(error.message)})
}

...

my php code


class SearchController extends Controller {
    public function Search(Request $request)
    {
        $query = $request->input('query');
        $accounts = Accounts::search($query, null, true, true)->get();
        return response()->json($accounts);
    }
    ...
}

like image 308
pikanerd Avatar asked Sep 20 '25 05:09

pikanerd


1 Answers

I don't know exactly how the Axios cancellation works, but if the client disconnects the HTTP session (as it should) you could try using the ignore_user_abort setting.

public function Search(Request $request)
    {
        ignore_user_abort(false);
        $query = $request->input('query');
        $accounts = Accounts::search($query, null, true, true)->get();
        return response()->json($accounts);
    }

Other useful functions could be:

connection_status: Check the current status of the connection

connection_aborted: Check if the connection has been canceled


I just want to add that your function does not seem very intensive, so I'm not sure how useful such a check is. As Tauqeer suggested in the comment, the usual approach in those situations is to apply a debounce to your javascript search function, in order to only fire the request when the user finished typing.

An example using lodash:


const search = (query) => {
    .. your axios request ...
}

const fetchData = _.debounce(search, 300) 

Now you can just call fetchData(query) whenever the user types something and it will only send a request when the user stops typing for 300 milliseconds

like image 138
gbalduzzi Avatar answered Sep 22 '25 22:09

gbalduzzi