skip to Main Content

I’m having an issue I don’t understand. (I am new to php and jquery). I can not seem to get a function to return false, it will return null when passed to something in jq.

I am calling the function with this:

$.ajax({
    method: "GET",
    url: "/auth/check/",
    success: function (response) {
        alert(response);
    }
});

I have a function:

public function authUser()
{
    $r = false;
    if (Auth::check()) {
        $r = true;
    }
    return $r;
}

or within a route, both do the same thing.

Route::get('auth/check',function() {
    return (Auth::check()) ? True : False;
});

With dd i can confirm they do result in either false or true. However the response to my jq is null when it is returned.
However if i change false to something else, say a string ‘test’ it will return ‘test’.

I can get around this by changing return to 0 when I want it to be false but I am wondering what causes this behavior?

2

Answers


  1. You need to return false as a JSON object :

    Route::get('auth/check',function() {
         $authStatus = (Auth::check()) ? True : False ;
         return response()->json([
            'isAuth' => $authStatus
        ]);
    });
    

    To access it with your javascript use :

    ...
    
    success: function (response) {
        alert(response.isAuth);
    }
    ...
    
    Login or Signup to reply.
  2. If you return a string instead of a boolean, Laravel should convert it into a full response and return it to the client

    Route::get('auth/check',function() { return (Auth::check()) ? 'True' : 'False'; });
    

    You can return basic string or arrays from the controller and have the response automatically generated. If you want more control, you can create the response object yourself. You can read more about it here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search