Introducing Eloquent ORM 0:00Hi everybody, welcome to day 9 of 30 days to learn Laravel. You're doing great. And I'm really excited for this one because I get to introduce you to Eloquent. And Eloquent really is one of the pillars of the Laravel framework, and I really do think you're going to love it. Jargon alert, Eloquent is an ORM. Not an ORV, not an SUV, an ORM. And this stands for Object Relational Mapper. Here's how you think of it. An ORM maps an object in your database, like a table row, to an object in your PHP code.Here's how you think of it. An ORM maps an object in your database, like a table row, to an object in your PHP code. So think about it, we can go into TablePlus and view the details for a single record, a row. Wouldn't it be cool if that record just had some kind of representation in your PHP code? Just like I can see a comment or a post within my database, what if I just had a post object that included all of those details? Well, that's sort of what you can think of when we reference the term ORM. Or you might have heard of ActiveRecord. This is Laravel's ActiveRecord implementation. Converting Class to Model 1:14Or you might have heard of ActiveRecord. This is Laravel's ActiveRecord implementation. And again, you're going to love it. So let's have a look. Okay, so return to your editor and open up your job class. I want to convert this into an Eloquent model. And it's really simple. But first up, this data here is superfluous, right? It's being stored in the database. We don't have to double up.It's being stored in the database. We don't have to double up. So I will remove that entirely just for now. Okay, so all I have to do to make a class, a PHP class, into an Eloquent model is to extend the model class. So I can say extends model. And you want it to be illuminate database eloquent model. So in my editor, that automatically gets imported as you see here. Okay, but notice immediately when I did that, we got this red squiggly line, declaration must be compatible with model all.Okay, but notice immediately when I did that, we got this red squiggly line, declaration must be compatible with model all. So as you can imagine, Eloquent has its own API for how we can query the database. And part of that API is a method called all. And also part of that API is a method called find. So you know what we can do? Yep, we're getting rid of it all. There's no reason to reinvent this wheel. Okay, fun. So now let's play around. Querying with Eloquent 2:28Okay, fun. So now let's play around. Let's go into the routes file. And yeah, within the home route, we're just temporarily going to try out some queries. So I will reference our job model. And notice we have all of these methods that we can call due to the fact that we extended that model class. So let's try out job all. And let's just see what happens. Is that instantly going to give me all of the records from that job listings table?And let's just see what happens. Is that instantly going to give me all of the records from that job listings table? Well, let's see. We'll try to get our jobs, and then we will die and dump the response. Okay, to the browser. All right, well, I do see a collection, but notice the items are empty. So we have an empty collection, and we know that's not right. So what's the problem? Okay, well, here's a key thing to understand. Laravel and Eloquent, by extension, rely heavily on conventions. Fixing Table Conventions 3:14Okay, well, here's a key thing to understand. Laravel and Eloquent, by extension, rely heavily on conventions. So if we switch back, if we have a job Eloquent model, Eloquent is going to assume that you have a table called jobs. But if I switch to TablePlus, the table isn't called jobs. Because remember, we had a little bit of a collision there, didn't we? Laravel already includes one out of the box called jobs. So we had to tweak ours. Okay, so we have two choices to resolve this. One would be to rename this to job listing.Okay, so we have two choices to resolve this. One would be to rename this to job listing. And notice how the name of the class is the singular form of the table. So if you had a table called comments, your Eloquent model would be comment. If you had a table called posts, then your Eloquent model would be called post. Right? That's an important thing to keep in mind. So we could do this, or in situations where you want a unique table name, you can add a protected property called table, and then here I can assign it job listings. Okay, so now if I switch back to the browser, now we have a collection of three items. And check this out.Okay, so now if I switch back to the browser, now we have a collection of three items. And check this out. Each item itself is an instance of that new job class. So now we have a place to tuck any behavior that's related to a job. Whereas before, we didn't have that. We were just dealing with simple scalars. There was nowhere to put that logic except in your routes file, which doesn't quite make sense most of the time. Okay, so if we scroll down, you'll see there's an attribute section that has information about the title and the salary for this particular row.Okay, so if we scroll down, you'll see there's an attribute section that has information about the title and the salary for this particular row. If we go to the next one, this one I believe is programmer. And then, of course, the third one would be teacher. Okay, so check this out. If we go back to my routes file, if I want to grab the first item, well, we have a couple ways to do it. So jobs is a collection as we've seen. And one way that we can interact with that collection is to treat it as if it were an array.And one way that we can interact with that collection is to treat it as if it were an array. So that means if I want the first job, I can just grab the first index within that array, so to speak. Okay, so if we come back and we scroll up and give it a refresh, now I don't have a collection, I have a single job instance that contains these attributes. And if I want to grab one of these values, I just reference it directly like this. Title, director, salary, $50,000. If I want to grab the next item, I can just do one. And this will be $60,000.If I want to grab the next item, I can just do one. And this will be $60,000. And the title is programmer. Cool. So you see how easy that was? We were able to entirely strip our little API that we built in that job class because Eloquent includes it and way more directly out of the box, which is really cool. So I want to see now if I can reproduce our list of jobs. So right down here, when the user visits slash jobs, we fetch them all and then we load a view called jobs.So right down here, when the user visits slash jobs, we fetch them all and then we load a view called jobs. So I wonder, will this just work right out of the box? I think it should. So back to the browser, let's click on jobs and it just works. But now we're no longer hard coding that array. OK, what about a single job? Yep, that one works just as before. Very cool. Now, we're not quite ready for forms yet, but we're going to tackle that very soon. Using Tinker for CRUD 6:42Very cool. Now, we're not quite ready for forms yet, but we're going to tackle that very soon. But of course, we can also use Eloquent to insert or delete records from the database. So I'll show you a new way that we can play around here. Open up your command line, then run php artisan tinker. Think of this as your command line playground for your Laravel app. It's a great way to get your bearings and try things out and see, does this work the way I expect it to? You can create variables, you can grab them, you can manipulate things, you can make sure, like I said, that when you call this function, is it returning what you expect?You can create variables, you can grab them, you can manipulate things, you can make sure, like I said, that when you call this function, is it returning what you expect? Let's play around and see if that works. This is a good place to do that. So, why don't we play around with Eloquent? App, models, job. And if I want to create a job, we call a method create. It's all incredibly readable. So for the values, we can provide an array here. So a job listing has a title.So for the values, we can provide an array here. So a job listing has a title. So I'm just going to say Acme director. And then a salary is going to be one million, million dollars. And I believe those are the only ones we have here. All right. So you call a create method, you pass an array, and you include all of the relevant columns that your table will require. So if we run that, though, we get a mass assignment exception. To be honest, I wish this didn't happen out of the box, because I think it is immediatelySo if we run that, though, we get a mass assignment exception. To be honest, I wish this didn't happen out of the box, because I think it is immediately confusing to newcomers, and it requires a bit of knowledge that you may not have yet. Now, effectively, what's going on here is Laravel is providing some safety and security out of the box. It's saying, hey, you might want to be a little bit careful about mass assigning these attributes all in one go. And that's exactly what we did here, by the way. And it's fine if you know what you're doing. But again, Laravel is just trying to keep you on the straight and narrow.And it's fine if you know what you're doing. But again, Laravel is just trying to keep you on the straight and narrow. So yeah, what's the potential danger? In real life, you will often be responding to a form request, right? So you could have a form to update the title of a post. The user submits that form, and you could potentially just pass the array of those form attributes to this create method. But, you know, rule number one when dealing with users is you have to assume they are malicious and they're trying to do something wrong. So what if they tweaked that form request to also update the author ID of the post asmalicious and they're trying to do something wrong. So what if they tweaked that form request to also update the author ID of the post as well? And you didn't know that. You didn't ask them to do that, but they snuck it in anyways. Well, if you then blindly pass that array of attributes to the create method, you're no longer updating the title of the post like you thought. You're also updating the author of the post, which could be catastrophic. Now imagine a scenario where you're updating the admin status for a user and you didn't even know you were doing it.Now imagine a scenario where you're updating the admin status for a user and you didn't even know you were doing it. So this is what Laravel is protecting against. As long as you are thoughtful and you know exactly what data is being passed to the create method, it's entirely safe. But that being said, Laravel by default protects you against this, and you either have to turn off the feature or do what we're about to do right now. Notice after the red warning, I see add title to the fillable property to allow mass assignment on the job class. OK, so I'll show you what that looks like.on the job class. OK, so I'll show you what that looks like. I can command click to go to the job class, and we can add a property called fillable. This represents all of the attributes that are allowed to be mass assigned. So for example, if I wrote title and salary, this means these two items and these two items alone may be mass assigned. So if that malicious actor tries to update the user ID as well, well, it would be as if they never did it, because it will be ignored entirely when we pass it to that create method in this example. OK, so let's come back.in this example. OK, so let's come back. I'm going to hit control C to exit out, and then we will open PhpArtisan Tinkerer one more time. All right, and now rather than rewriting this by hand, you can usually press the up arrow key to cycle between your old commands. OK, so if I run it now, it's going to work. There we go. So it creates the record within the database table, and then it returns to you a new job instance that includes all of those attributes.So it creates the record within the database table, and then it returns to you a new job instance that includes all of those attributes. OK, very cool. So let's inspect all of our jobs. Job all, and we should have four items, and we do. We have the initial three that we created, and we have our fourth one. And also notice in this case, because we're going through Eloquent, it will automatically set these default timestamps, which is very cool. All right, so we now know the all method. We know the create method.All right, so we now know the all method. We know the create method. But what about that find method that we manually created an episode or two ago? Well, of course, we can use that as well. I'll show you. App, models, job, find, and we need to give it a unique identifier. So that's why most tables will include some kind of unique ID, as you see here. So if I want to find this new one I created, I could say find seven, and that will return to me that record from the database. So keep in mind what's going on here.to me that record from the database. So keep in mind what's going on here. It's not magical. A SQL query, of course, is still being executed at some point behind the scenes. But yes, sometimes it does feel magical. And you know what? It effectively is magic. The Eloquent code base is very, very, very, very, very, very, very, very, very, very complicated and confusing. I don't know what I'm seeing when I look at it.and confusing. I don't know what I'm seeing when I look at it. But that's the great thing. I don't have to know what's going on there. It just works. So now, rather than memorizing or learning how to write these potentially confusing SQL queries, Eloquent tucks that away behind a nice API. I have a method called all to fetch all the records. I have a method called find to find a specific record. Of course, I can add conditions like where.I have a method called find to find a specific record. Of course, I can add conditions like where. I can add joins. I can do anything I can imagine behind this nice, clean API. All right, so if I go back to TablePlus, let's give this a refresh. And now we see our new record. So what I'm going to do is go ahead and delete these old ones. And we'll stick with only the ones that were generated through Eloquent. And that's fine. But now if I switch back, if I want to delete this job, then I could simply say job delete.And that's fine. But now if I switch back, if I want to delete this job, then I could simply say job delete. Whoops, forgot the dollar sign. One more time. And notice that returns true to indicate it was successfully deleted. If I switch back, give it a refresh, now it's gone. Okay, so I think we're in pretty good shape now. You've had your first introduction to Eloquent. The only remaining thing I want to show you is that in this example, we already had a job class that we converted into an Eloquent model. Generating Models and Migrations 13:34The only remaining thing I want to show you is that in this example, we already had a job class that we converted into an Eloquent model. But most of the time, you will be starting from scratch. So here's what I want to leave you with. And this will be your homework as well. If I run php artisan make, you'll see there are a bunch of make commands. And you learned in the last episode, these are used to generate files. So as you can imagine, there is a make model commands. Now often these will accept certain arguments, but it's hard to know which arguments those are.Now often these will accept certain arguments, but it's hard to know which arguments those are. So I'll show you a tip. If you add help before any of these commands, it will give you help for the command. Shocker. Alright, so now if we scroll up at the very top, we can see all right, we can provide the name of the model. And then we have various options that we can include. So when we generate a new model, this is often the the start of a new concept in your application. So it's a great entry point for also constructing other things.So when we generate a new model, this is often the the start of a new concept in your application. So it's a great entry point for also constructing other things. And that's why we have these options like dash C, to also create a companion controller for the model or a factory or a migration or a policy or a seeder. You don't know what a lot of these are yet, but you will soon. So notice the one at the top dash A or dash dash all which is the long form, it would generate a migration, a seeder, a factory, a policy, a resource controller and a form request in addition to the model. So you don't necessarily need to do this yet, because you don't know what half of these are.So you don't necessarily need to do this yet, because you don't know what half of these are. So I want you to know that when you start working on these, these new ideas, and you add new sections of your site, you wouldn't start by creating the migration, you'd probably start by creating the model. And then the model would create the migration as part of as part of its logic, that's something to think about. Okay, so out of the box, and we're not going to keep this, if I were to say make model comment, notice that will create a new file within your comments directory, and you'll see it right here.comment, notice that will create a new file within your comments directory, and you'll see it right here. And notice it extends model, it uses this trait called has factory, we're not quite ready to talk about that just yet. But you can you can leave it where it is, with the understanding that you'll learn more in the future. Okay, let's do another one. And again, keep in mind, I'm not going to keep any of these, I'm going to delete them all at the end of the video. Let's do make model post.all at the end of the video. Let's do make model post. But this time, I want to also create a migration. Notice I can add dash m for short. So let's do that now, dash m. And now it creates two files, it creates the model, but also corresponding post table migration. Let's have a look at that post looks good. And then migrations, of course, go in the database folder, and I can see it right down here. So notice, these these generators give you a way to quickly and rapidly start constructinghere. So notice, these these generators give you a way to quickly and rapidly start constructing some of these new features, which is cool. So I could say a post consists of a title, it consists of a body, but a string is too short, that would max out at 255 characters of our car. Instead, we're going to use text because it could be a very, very long blog post, and we want to allow for that. So yeah, you're starting to get comfortable, right? We are generating models, we've learned about options to also generate corresponding migrations. And as you learned in the last episode, you can run php artisan migrate to commit thatWe are generating models, we've learned about options to also generate corresponding migrations. And as you learned in the last episode, you can run php artisan migrate to commit that migration. So that is now relevant and visible within your database. So you're making really good progress here. I hope you're excited. And yeah, this is all just so incredibly useful and powerful. I can't stress it enough. This is the bedrock of so much of the Laravel code you will write even 20 years from now. Okay, so your homework is, yeah, work on it.This is the bedrock of so much of the Laravel code you will write even 20 years from now. Okay, so your homework is, yeah, work on it. Get this into your fingertips, play around, you can delete it all when you're done, generate a variety of models, practice also generating the migrations as part of those models and then fill out the migration and then run php artisan migrate to see it in the database and then start writing queries using php artisan tinker to fetch items from that database and then see if you can manipulate an item or delete it or add a new one. That's your job. So play around and get these keystrokes under your fingertips. All right.So play around and get these keystrokes under your fingertips. All right. I'll see you in day 10. Is that right? Yes, tomorrow is day 10. So we will next talk in day 10. All right. See you later. In day 10.In day 10.