Introduction to Controllers2:40 with Jonathan Barrios
What is a Controller? Over the next several videos, we’re going to explore Controllers and how they fit into an MVC application. Instead of defining all of the routes using Closures inside of your route files, you can also use Controller classes. Controllers are located in the app/Http/Controllers directory. Let's get started!
[MUSIC] 0:00 Welcome back. 0:04 Over the next several videos, we're going to explore controllers and 0:05 how they fit into an MVC application. 0:10 Instead of defining all of the routes using closures, 0:12 instead of your route files, you can also use controller classes. 0:15 Controllers are located in the app/http/controllers directory. 0:20 Currently, we're using the default Laravel route that returns the welcome page, 0:28 and the routes file web.php, we're going to replace the closure with a controller. 0:33 Remember, controllers always return something and 0:38 act as a middleman between the model and the view. 0:42 First we need to create a controller using artisan so 0:45 we can connect the models to the controller. 0:49 See you there. 0:51 To build controllers, we'll use some of the artisan CLI commands that we've 0:53 already learned from the previous section. 0:57 In the terminal, use this command to create a controller. 1:00 PHP artisan make controller AppController. 1:08 Remember, the app controller at the end of the command is the name of the controller, 1:13 which can be whatever name best fits your project. 1:18 You could also use the optional R flag, 1:21 which tells artisan to create this controller as a resource controller. 1:23 Resource controllers are made with all of the crud goodies built in, 1:28 which we'll cover later in the course. 1:32 If you don't need crud functionality, just omit the R flag and 1:34 artisan will create a regular controller, super simple. 1:38 Now that we've created our controller using the artisan command, 1:43 open the appcontroller.php file located in the app forward slash 1:48 http forward slash controller directory. 1:52 Sweet, artisan made us controller, thanks artisan. 1:58 MVC might seem a bit overwhelming at first. 2:03 But as we continue to break down each component, 2:06 they'll quickly understand how Laravel uses the MVC design pattern. 2:10 At their core, controllers control the flow of our applications. 2:14 For example, when a user requests the library page, 2:19 the request goes from the route to the app controller, 2:23 which acts as a middleman and returns the views with the models mix together. 2:26 That's a mouthful, but it's that simple and in that order. 2:31 In the next section, we'll finish creating the app controller. 2:35 See you there. 2:38
You need to sign up for Treehouse in order to download course files.Sign up