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
there are two operators involved:
null safety
?->
which either returns value ofid
property or null ifuser()
is nullternary
?:
which checks first part and returns it, if it is true or last argument if falseso, conversion to old syntax should look like this:
note: it is very important distinction between this code and yours – if id property is null while user() is not
On ternary operator
will results in 5, this is a short hand.
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: