skip to Main Content

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!!!

2

Answers


  1. 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

    Login or Signup to reply.
  2. On ternary operator

    <?php
        $a = 5;
        $b = $a?:0; //  same as $b = $a ? $a : 0; and $b = $a ?? 0;
        echo $b;
    ?>
    

    will results in 5, this is a short hand.

    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?

    YES, and the rate limiter utilizes your default application cache as defined by the default key within your application’s cache configuration file. However, you may specify which cache driver the rate limiter should use by defining a limiter key within your application’s cache configuration file:

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