در حال بارگذاری ...

Intro to throttling0:00

If I visit my route /web file, you're likely already familiar with the concept of throttling. This is especially useful for APIs. For example, maybe you want users to be able to query all of your posts or something like that, but they can't just hit your API a thousand times a minute. You need some way to throttle them to protect yourself. Well, Laravel can help you with that out of the box, and this comes long before Laravel 5.6. But anyways, we could say, well, you can query, just for the demo, four times over the course of one minute.

Throttle middleware settings0:29

But anyways, we could say, well, you can query, just for the demo, four times over the course of one minute. Okay? And if you're curious about that, we can quickly take a look at throttle requests. Here's a middleware. And if we scroll down to the handle method, you can see that first argument is the maximum number of attempts, and then the second argument is the decay minutes, how long before it decays and resets. Okay, so this means you can hit this route four times in one minute. But if you go five times, nope, we're not going to allow that.

Testing rate limit behavior1:24

Okay, so our decay was one minute, which means if I give this a refresh, we should be back in business. And once again, if we refresh it a handful of times, on that fifth try, once again, we get too many requests. Okay, so now what's new in Laravel 5.6 is that we can specify an attribute on the authenticated user. And this can be especially useful in situations where maybe a guest user has a basic number of requests they can make. But if you're a premium user or a paying user, well, your threshold or your throttle limit increases substantially, right?

Dynamic limits per user2:19

So the important thing to understand is this will be dependent upon the authenticated User. And in this case, we don't have one. So let's simulate one right now. We'll just say, give me the first User in the system and log that person in. Next, I'm going to switch over to that User and I'm going to set a public property here, we called it rateLimit. And yeah, I'm going to hard code it in this case, but that can be dynamic, it can be an accessor where you perform some calculation, anything you need to. Now if we switch back, we should be able to request this page five times over the course of one minute.

Verify dynamic rate limiting2:49

Now if we switch back, we should be able to request this page five times over the course of one minute. So one more time, we'll give it a refresh, one, two, three, four, five. And on try number six, no more requests. And that's all there is to it. So yeah, brand new in Laravel 5.6 is dynamic rate limiting.

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟