Home > Mobile >  How to avoid php getting vuejs params as string when it is undefined or null
How to avoid php getting vuejs params as string when it is undefined or null

Time:11-18

That is maybe a dumb question or asked many times (if so, answer with existing link and I will close this post).

Let's say in laravel by example, when send model id in route, everything is ok in php. But when a route must optional parameter defined as null in Vuejs (or undefined), Php gets this parameter as string.

//vuejs in methods:
myFunction(id1, id2 = null) {
  axios.post(`/api/model1/${id1}/model2/${id2}`)
    .then((response) => {
        console.log(response);
    })
    .catch(err => {
        console.log(err);
    });
 },

And

//Laravel routes/api.php for my api
Route::post('model1/{id}/model2/{id2}', 'SomeController@doThis');

Example: myapi/model1/{id1}/model2/{id2} and myapi/model1/987/model2/null

So I get 'null' here for model2. (sometimes it is 'undefined' according to the situation)

What is the better way to deal with it? without adding regex for my parameters? because I do not need regex for the first param what is id1.

I try to deal with it many times, but it seems I always come back to this problem from time to time. I need to keep this in my mind once for all.

CodePudding user response:

You should do null checks when constructing the URL:

//vuejs in methods:
myFunction(id1, id2 = null) {
  axios.post(`/api/model1/${id1}/model2${id2 ? `/${id2}` : ''}`)
    .then((response) => {
        console.log(response);
    })
    .catch(err => {
        console.log(err);
    });
 },

CodePudding user response:

How making the your laravel route parameter as an optional : Optional Parameter

Route::post('model1/{id}/model2/{id2?}', 'SomeController@doThis');

add the ? at the model2 parameter.

  • Related