تماشای این درس نیاز به اشتراک حرفه‌ای دارد.

Return Types from Routes0:00

You may know that in response to a route, you can return a variety of formats. For example, I could return a string, and it'll work. If we run that in the browser, sure enough, that's converted to the proper response. But we could also return an array, and that too will work. Notice here, we set the content type appropriately, and this is the raw data that is sent through. Now we could also call the response helper, if you like that, if you think it's a little more clear. Come back, that too will work. You could return just a couple more. You could return a new instance of a model, and that too will work.

You could return just a couple more. You could return a new instance of a model, and that too will work. Come back, refresh, and that gets converted to JSON, and the same is true for a number of things. For example, if you have a Collection, if that's returned from the route, it too will be converted to JSON. What else? Maybe two more. Well, of course, you can return a view itself that will be rendered, but you could also, let's try this, let's return an anonymous class, and in this case, Laravel won't know

Making Objects Responsable0:59

Well, of course, you can return a view itself that will be rendered, but you could also, let's try this, let's return an anonymous class, and in this case, Laravel won't know what to do. It can't even find a toString method, so it gives up. We could fix that in a couple ways. One, we could define a toString method, so this determines or declares how this object will be cast to a string, and yeah, that'll work. Or what we could do is implement the Responsable trait, and then if I implement the toResponse method, this too would be one way to go. Come back, refresh, and that works as well.

method, this too would be one way to go. Come back, refresh, and that works as well. So in this case, any object that implements the Responsible trait, and all that has is the single method. So any object that implements that method can be converted to a proper response. Okay, so very cool. Have you ever wondered, how is Laravel doing this? How is it checking for it? Well, let's go through it together. Let's begin with something very basic.

Tracing the Request Lifecycle2:00

Well, let's go through it together. Let's begin with something very basic. We'll return an array. All right, let's dig through the code piece by piece and figure out how that is converted to JSON. We'll begin at the entry point, which is public/index.php. Think of this very much as the entry point into your project. Okay, so we pull in Composer's autoloader, all good. Now we require this bootstrap/app.php file in your project, and the first thing we do is instantiate the Application class.

Now we require this bootstrap/app.php file in your project, and the first thing we do is instantiate the Application class. Now here's what's cool about this class. Notice it extends the ServiceContainer. So your Application class is a container, which means if you're ever toying around, you can access the application by using the app helper function. This is a container. So you could bind things into it. You can resolve things out of it. Okay, let's switch back.

You can resolve things out of it. Okay, let's switch back. We instantiate our app. We bind some important things into that service container, like the Kernel class. So the kernel, in many ways, this is the HTTP core for Laravel. We'll talk about that more in a minute. Next we return. Okay, so at this point, we've built up our Application class. We've bound some initial providers and keys that are stored as singletons here. Now if we come back, we have our app.

We've bound some initial providers and keys that are stored as singletons here. Now if we come back, we have our app. So let's take a look. At this point, we have an application instance. Okay, let's keep going. Next we need to run the application. So we resolve that kernel. We just bound it earlier. We're resolving it out of the container, and then we are handling the incoming request. So using Symfony, ultimately, we can capture the current request like this.

We're resolving it out of the container, and then we are handling the incoming request. So using Symfony, ultimately, we can capture the current request like this. So now we're telling Laravel, I have your application. We're going to resolve the kernel, and the kernel needs to handle this incoming request. Let's see how it's doing that. Go to the kernel. Let's go to handle. Okay, handle the incoming request. So a lot's going on here. We're going to move pretty quickly, and I'll show you the bullet points, okay?

response, and then ultimately this is just going through any of your middleware that are terminable. So if a middleware has a terminate method, this will be called only after the response has been sent. Okay, but anyways, we're understanding a little more, but I want to go back to that handle method here. So let's go back to our Kernel, and we need that handle method. Okay, so we're going to send the request through the router. This is what I want you to see. So you'll see this pipeline section here, and as it turns out, much of Laravel is channeled

Kernel Pipeline and Middleware5:11

This is what I want you to see. So you'll see this pipeline section here, and as it turns out, much of Laravel is channeled through this pipeline component. It effectively provides a fluent interface for sending a request through a series of handlers or middleware. Let's read it out. We have a new pipeline that will send the incoming request through a series of middleware, and each of those will have the opportunity to handle and respond to the request in some form, and then ultimately, once all of those have been completed, we will dispatch to the router.

form, and then ultimately, once all of those have been completed, we will dispatch to the router. Okay, so what are these middleware? Well take a look at your Kernel class. See all these middleware? These are global middleware that will fire for every single request. And if middleware is a bit of a scary word, just think of it as handlers. Each of these classes are little handlers that can respond to the request, almost like you're peeling back layers of an onion as you make your way to the core of your application. So things like this.

you're peeling back layers of an onion as you make your way to the core of your application. So things like this. Here's one. Check for maintenance mode. This will receive the incoming request, and it'll check to see, effectively, have you run php artisan down? If so, we need to throw a maintenance mode exception. And that's it. That's one handler, or one layer of the onion. Let's go back.

That's one handler, or one layer of the onion. Let's go back. Here's another one. We validate the post size, or convert empty strings to null. All of these will run for every incoming request, which means if you have something special you need to do, create a new middleware using php artisan make:middleware, and then you can add it here. Okay, let's get back to work. So we are sending the request through all of this middleware, and then we dispatch it to the router.

Routing and Dispatching Requests6:47

So we are sending the request through all of this middleware, and then we dispatch it to the router. So here, we're deferring to a Router collaborator, and we're calling the dispatch method on it. So now, we're in Illuminate\Routing\Router. Dispatch the route. Let's just go through this rabbit hole here. All right, now we're starting to get somewhere. So we're going to track down the route. Notice here we have a routes collection. We're basically going to look at the incoming route, and we'll check, well, do any of those

Notice here we have a routes collection. We're basically going to look at the incoming route, and we'll check, well, do any of those routes match up with what we have defined in this file? And if so, let's come back. Let's run the route. Let's see. What does running the route mean? Well, we set a dependency. We fire an event. But yeah, here is what you want.

We fire an event. But yeah, here is what you want. Okay, so at this point, we have tracked down the route. So for example, if I die and dump the route, come back, refresh, there we go. We found the matching route. And you'll see here for the action, we're not using a controller action. Instead, we have a closure that can be triggered. So let's keep going. We now run the route within the stack. So that means your route will now be sent through the pipeline once again.

We now run the route within the stack. So that means your route will now be sent through the pipeline once again. But how come? Let's see. We determine if we should skip the middleware. Again, I don't expect you to follow every single line here. There's a lot to take in. Think of it more as a zoomed out flyby. So once again, we instantiate the pipeline. We send the request through all of the route middleware.

So once again, we instantiate the Pipeline. We send the request through all of the route middleware. And then once those are complete, we run the route and prepare the response. Okay, almost done. Let's see how we run a route. Well, we figure out, are we triggering a controller action or do we have a callable in the routes file? In this case, we have a callable. Let's see. We take a look, and we are physically calling that function there.

Let's see. We take a look, and we are physically calling that function there. So if I go back to my routes file, we are now calling this function and gathering the response from that function. Okay, so now if we come back, we can prepare the response. And here is what you've been waiting for. Here is where we receive a response of some form. Again, it could be a string. It could be an array. It could be a model.

Converting Data to Responses8:54

It could be an array. It could be a model. It could be a collection. It could be a responsible object like you see here. Take a look at this. So if I switch to Firefox, in this case, it's an array. Yeah, if I return something else, now it's a string. So it has not yet been converted to a proper response. We just have a data type at this point. Okay, let's figure out what to do.

We just have a data type at this point. Okay, let's figure out what to do. If it implements that Responsable contract like we reviewed at the beginning of the video, then all we have to do is call toResponse on it. And we have the actual response type that we want. Okay, next we can continue on. Do we have a PSR response interface? No. Next, do we have a model? So did we return a newly created model as you see there?

Next, do we have a model? So did we return a newly created model as you see there? If so, we need to create a new JSON response and also set the status code to a 201 created. So let's think. Let's return a new instance of User and we'll set the name. So in this case, the model was not recently created. So we're not going to get a 201. However, if I come back here, we do another check. If we don't have a symphony response, but the object we're dealing with is arrayable or JSONable or array object, so that allows you to interact with an object as if it was

If we don't have a symphony response, but the object we're dealing with is arrayable or JSONable or array object, so that allows you to interact with an object as if it was an array. That's what array object allows for. And then also JSON serializable. So as it turns out, any of your models will implement most of these. Take a look. Let's go to User. It extends the parent User class, which extends the Model class, and then there you go. It implements arrayable and array access and JSONable and JSON serializable.

It extends the parent User class, which extends the Model class, and then there you go. It implements Arrayable and ArrayAccess and Jsonable and JsonSerializable. So that's what we want. If we switch back, oh, and it also handles the situation where you return an array. Okay. All of those will be converted to a JSON response. And most importantly, we know how to set the data here. So we have that response, and we figure out, okay, should I call a toJson method on it? Should we simply run it through json_encode? Should I call a toArray method on the object?

Should we simply run it through json_encode? Should I call a toArray method on the object? You get the idea. Okay. So now we're starting to understand how the response is being created. And then finally, for things like this where we return a view, all right, well that will be wrapped within a Response class. The last step is to prepare it, and that's basically where all of the necessary headers will be set. Okay.

will be set. Okay. So a lot to go through there. I don't expect you to follow all of it. But you should have a better understanding now that a request comes in. We then resolve our kernel, and we tell the kernel to handle it by sending the request through all of the necessary middleware. That will generate a response. So at this point, if I die and dump our response, let's see what we have here. In this case, we should have a standard response instance, and we do.

So at this point, if I die and dump our response, let's see what we have here. In this case, we should have a standard response instance, and we do. If I bring it back to what we had before, that should be a JSON response, and it is. Which means if you want, you could return your own JSON response here. Like so. Refresh, and there you go. So the only remaining piece of the puzzle, if we switch back, is we send the response, and we've already touched on this. We send the response by setting the headers and echoing out the content. And that's it.

We send the response by setting the headers and echoing out the content. And that's it. So now you know, if I were to return an array from a route, well, Laravel's going to look at this. And its router, let's see if we can find it, it'll do a series of checks. And among those, it'll say, okay, did you give us an array? If so, you probably want to return JSON. So I will wrap it within a JSON response. And then that JSON response will figure out how to encode it. And in this particular case, it'll simply run it through json_encode.

And then that JSON response will figure out how to encode it. And in this particular case, it'll simply run it through json_encode. And that is what will be sent to the browser. Very cool.

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