Search code examples
phplaravelconditional-operator

how to understand this sentence in laravel


Im trying to understand what the sentence $request->user()?->id ?: $request->ip() does in this function

protected function configureRateLimiting()
{
    RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });
}

According to my understanding it will limit the rate attempts to 60 by minute by either user id or IP address if there is not user logged in, Am I correct?

But then how will the ternary translates to a classical if sequence? something like this?

if (null !== $request->user()) {
    $request->user()->id;
} else {
    $request->ip();
}

Its the first time i see a ternary used in this way, can you give me some more examples of this use?

Thanks for your help!!!


Solution

  • there are two operators involved:

    • null safety ?-> which either returns value of id property or null if user() is null

    • ternary ?: which checks first part and returns it, if it is true or last argument if false

    so, conversion to old syntax should look like this:

    $tmp = null;
    if ($request->user() != null) {
        $tmp = $request->user()->id;
    }
    if ($tmp) { // note id can be null theoretically
        $tmp = $tmp; // this part is hidden in `?:` effectively
    } else {
        $tmp = $request->ip();
    }
    return Limit::perMinute(60)->by($tmp);
    

    note: it is very important distinction between this code and yours - if id property is null while user() is not