Why Use Eloquent Models
Okay then gang. So far we have created a database and we've hooked that up to our Laravel app and we've used migrations to create tables in that database. Now ultimately we want to store data in those tables. For example, in the pizzas table that we created we want to store pizza records and then we want to be able to interact easily with that data in our code and do things like get data, save data, update data, etc.
Now if we wanted to, if we have the inclination, we could use SQL commands to do it manually. But in Laravel there's an easier way to do it and that is by using what's known as Eloquent models. But first of all, what is a model? Well, a model in programming is normally a class or an object blueprint that represents a certain type of data. For example, our pizzas table right here is going to store a certain type of data: a pizza record which has a type property, a base property, a toppings property.
Now in Laravel we can create an Eloquent model to represent that type of data, a Pizza model, and then if we want to interact with that type of data in the database we'll use that model to do so. Now under the hood Eloquent uses SQL to interact with the database, but it also wraps all of that in an extra layer and it provides us with a bunch of easy-to-use methods on the model to read and write to the database. So it's intended to abstract away from complex SQL code and instead provide us with a simple programmatic interface with simple methods we can use instead, like find and save and get.
So in a way you can think of a model in Laravel as a code representation for a specific table in our database. So we'd have a Pizza model like this to represent a pizzas table and if we had another table to store something like articles then we'd make an Article model to represent that table. And if we want to interact with the pizzas table to do something like save a new record or retrieve records we'd use the Pizza model to do that on one of these methods. And if we want to interact with the article table we'd use the Article model to do that.
Inserting Sample Pizza Records via phpMyAdmin
Hopefully now you've got a basic idea of what an Eloquent model is. Let's try creating one in our project. So the first thing I'm going to do is manually add a few records to our pizzas table and I'm doing it manually through phpMyAdmin because we've not yet learned how to do it programmatically using Eloquent models. We will see all of that later, but for now, so we have some data to play with, I'm going to add it manually.
So I clicked on this pizzas table right here, then I'm going to go to Insert and I'm not going to bother with the first few columns but I'm going to come down to type. By the way I took off the price column, we don't need that in. So the type of this one is going to be Hawaiian and then the base is going to be cheesy crust and then the name, the person ordering, Shawn.
The second one down here we'll leave the ID, created_at and updated_at fields but then the type is going to be Hawaiian again. This time it's going to be garlic crust. I cannot spell gar like crust. And then finally the name is going to be Mario. And then finally I'll click on Go right here. So that should hopefully insert those two rows. If I go to Browse we can now see those right here.
Now I'm going to add one more I think. So let me go to Insert again and let's come to type and this one is going to be a volcano pizza and the base is going to be thin and crispy and this is going to be for Yoshi. All right so let's press Go there and insert that one. So let's go to Browse again and now we can see we have these three records here. So now we can start to play around with these records from our code.
Generating a Model and Retrieving Records
Imagine now that in our project we want to interact with this table and this data. Well, the easiest way to do that would be to make a new Eloquent model for this table, pizzas, and then that model would come baked with other methods that we need to interact with this table and the data inside it. So the question then is how do we create an Eloquent model? Well again we can use our T's and to do that. So down here I'm going to say php artisan and we use the make command and then this time it's a model and I'm going to call this Pizza with a capital P. That's just a convention. So I'm going to press Enter and this makes us a model and that model is inside the app folder up here at the top. You can see right here we have Pizza.php. We already also have a User.php model that comes baked with a Laravel and it makes it automatically for every new project you create, but this Pizza one we just created.
So this is a very, very simple file, just a class called Pizza which extends Model so it inherits all of the methods that we need to interact with the database table from this model. Now Laravel automatically hooks it up to the pizzas table and it does that by pluralizing whatever the model is called. But if you want to override what table it connects to you can do so inside this class and we do so by using a protected property called table and we set that equal to the name of the table that we want. So in this case it would try and find a table called some name. Now we don't need to do that because it's going to automatically connect to the pizzas table for us based on this name. So now this model, even though we've not really done anything to it, is ready to use and we can use it now to interact with this table to get the data.
So let's try doing that. Remember if we go to our routes file, if you go to /pizzas then the PizzaController is handling this and we're using the index action. Over in the controller this index action currently makes up a load of data and sends it into the pizzas view right here. So how about now instead of making up this data we reach out to the database using that new model that we just created and retrieve all of the data and then pass that into the view instead. So the first thing we need to do is actually use that new model inside this file. So we can say use and then it's App\Pizza. That means we can now use this Pizza model inside this controller.
So now down here, delete all of this junk, we don't want that anymore and instead we want to interact with the database using this Pizza model. So we're going to store the results inside some kind of variable. I'm going to call that pizzas and I'm going to set it equal to Pizza which is the model right here and we can use a method called all. So this method comes automatically on all models that we create. It doesn't matter that it's not defined inside our Pizza model right here; it's automatically inherited from this Model class.
Okay so this right here is going to look at our pizzas table because it's already hooked up to the pizzas table in the background and it's going to retrieve all of the different records inside that table and now they're going to be stored inside this pizzas variable. So now that is a collection of Pizza records. So we're still passing them into this view right here; we don't need to change that but we do need to go into the view. So let me do that. Open up resources and then views and then pizzas which is the view we're using.
Inside here we've still got all of this loop from when we learned about loops. We can keep the loop but I'm going to delete everything pretty much inside it except for that div tag. So now what I'd like to do is output say the name and the type and the base of each pizza. Remember to do that we use double curly braces to output a variable. We're still cycling through the pizzas and we're putting this for each individual pizza right here and this now refers to a single pizza record. So before when we made up the data ourselves each pizza was a pizza array, now it's a pizza object from the database. So what I can do is say pizza and then use from that the name property and that gets us the name because we have a name column.
Let's go back over here. After that let's output the type, so I'm going to say pizza->type like so, and then after that I'm going to output pizza->base like so. All right then, so hopefully this should work. I'm going to save this, I'm also going to save this as well, and then I'm going to go to our project. I'm going to refresh to make sure the server is still running. Yes it is. I'm going to go to /pizzas now and see if this works. And it does. We get all of this data from the database and now outputting it to our view. How simple was that using this new model we just created?
Querying Models: orderBy, where, latest and Wrap-up
Okay so there are other ways to get the data from the database, so let me just go through a couple of them for you. So again let's say pizzas this time is equal to the Pizza model and then we'll use a method called orderBy and you can probably guess what this does: it orders the results based on a certain column. So I can pass in a column name, for example the name column, and we're going to order the results based on that. But this time when you don't use all you need to add on the get method as well because this just finds a selection in the database and orders them then we have to get them. all automatically does that but if we use this we have to use get on the end to get the results. So this does pretty much the same thing but it orders them by the name now. So if I refresh you might see these reorder a little bit and we get an error and that's because I've only added one colon instead of two. So let me save that and refresh and now we can see these are in alphabetical order for the name.
Now if we want to change the order we can add a second argument to say descending instead of ascending and then or refresh and it goes in reverse order. Cool. And you could do this by any other column by the way; it could be the base or the type, that's absolutely fine.
Okay so let's do the next one. So we'll say pizzas again is going to be equal to Pizza and this time we're going to use a method called where. And what where does is allow us to select certain records from the table and based on a certain condition. So I could say, okay, well get us all the pizza records where type is Hawaiian or the type is volcano or the name is Shawn, and it gets us a collection of those pizzas that match that criteria. So let's do that. The first argument is what we want to match, what column, and that is going to be the type column and I'm going to say, okay, get the pizzas where the type is Hawaiian. So if we look in our database we can see that two of them are Hawaiian, these two, so it just gets this collection right here.
But again it doesn't actually retrieve them; we need to add on the get method to do that. So this finds the selection for us, this gets them. So let me save that now and come over here and refresh. We should only see these two right now and we do. Awesome.
Okay so there's one more I'd like to show you and to be honest it's not going to have a big effect on how we view the pizzas right now but it will do later. I just want to prep it now. So pizzas is going to be equal to Pizza and then use a method called latest and this orders the records that we retrieve from the database in date order, so the most recent first of all. Now it's not going to have any effect on us because we don't have that field filled with anything yet but later on when we add these different records programmatically using the model those will be filled up and it will take effect. For now it's just going to grab them all the same as this would do up here but let's just prep this for later. So we need to say get again and this should basically just get us all of the pizzas.
Let's come over here and refresh and we can see all of them again. So there we go my friends, that is how simple using these Eloquent models really is and that is a lot easier than creating a load of SQL code ourselves. So that's the basics of Eloquent models in Laravel and how we use them to interact with our database tables. Later on we'll be looking at how to use it to save new records to the database table as well but first of all I want to just take a little sidestep and go over a few naming conventions in Laravel before we start adding a load more files, so we'll do that next.