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

Switching to SQLite Database0:05

All right, well, welcome back. So in the previous episode, I mentioned that in this video I would show you how to switch over to a database, and we're gonna do that now. And you know what? I think you're really going to enjoy this. Okay, let's get going. So if I open up my sidebar, you'll see that we have a database folder, and within it we have some scary words like factories, migrations, theaters.

and within it we have some scary words like factories, migrations, theaters. And then I also see this thing called database SQ light. So Laravel, of course, supports multiple drivers. Uh, you could use my SQL, you could use SQL, you could use, there's actually a, maybe a half dozen choices you could reach for. But out of the box, it assumes a file-based SQ l database. Now, where is this configured? It's configured in this dot NV file.

Configuring the .env File0:50

Now, where is this configured? It's configured in this dot NV file. Think of this as a private location for you to specify your preferred environment, uh, configuration. And by environment, that could be, well, when I'm working locally, uh, not, not in production, but locally, do I wanna use this database? Do I want to, uh, cache in that way? Do I want choose to look this way? But maybe in production, we want

Do I want choose to look this way? But maybe in production, we want to use different configuration settings. So that's why you might have one ENV file for local development, and then another one entirely for your production environment. Okay, so in this case, this represents our local environment. I want debug mode turned on,

this represents our local environment. I want debug mode turned on, but in production, I want it turned off. You get the idea. So anyways, if I scroll down, we can see some options for our database connection. And again, it's defaulting to SQ light. So let's get going. Let's open the terminal and I'm gonna run PHP Artisan once again, and we get this overwhelming list of commands we can run. But yeah, once again, we're just gonna learn

Creating Database Migrations1:54

of commands we can run. But yeah, once again, we're just gonna learn them one at a time. So if we scroll up, the one you care about right now is make migration. A migration is related to your database. And I want you to think of these as version control for your database. Think about it. If you needed to create an ideas table, well, you can make a migration

Think about it. If you needed to create an ideas table, well, you can make a migration and you could specify all of the columns for that ideas table. And then six months from now, if you needed to add or append a new column to that ideas table, you could make a new migration. And at any point, if you want, you could roll those migrations back, you could reset them entirely and run them from scratch,

you could roll those migrations back, you could reset them entirely and run them from scratch, and you would still end up with the exact same database configuration. So let's get going. PHP Artisan Make Migration. So what are we gonna name this? In this case we're making a table. And what table? Well, I want a table to contain all of our ideas. And again, often you'll see a mapping between your resource name and the table name.

And again, often you'll see a mapping between your resource name and the table name. It doesn't have to be that way, but it's, it's common. So why don't we call this create ideas table? Alright, cool. So now you can see it created a table, uh, migration right here. So if I open my sidebar database migrations, now we have a better understanding of what that is. And sure enough, you'll see we have a few out of the box. Uh, these three are included when you install the framework.

And sure enough, you'll see we have a few out of the box. Uh, these three are included when you install the framework. So notice you get a user's table, um, with the installation. That's because most applications need users. So we provide this to you outta the box. And I want you to notice that it declares all of the columns, uh, programmatically. So we have a name column on our user's table, and that's a string. We have an email column and it should be unique.

table, and that's a string. We have an email column and it should be unique. We have an email verified at, uh, column, and that's a timestamp and we have a password. So this makes it incredibly easy to define these columns, uh, even if you don't know that much about, uh, databases or SQL or my SQL. Alright, anyways, let's open our ideas table and we can see that it's split into two methods and up and a down and up is when we run the migration.

and we can see that it's split into two methods and up and a down and up is when we run the migration. A down is when we basically want to unrun the migration. If we wanna roll it back, what would we need to do? So I, I'll tell you right now, some people just omit this entirely. They never include a down method, but other people swear by it. So you can play around with this and decide what you think. All right? Is it beneficial to be able

So you can play around with this and decide what you think. All right? Is it beneficial to be able to roll back your migrations or do you always wanna be moving forward? Okay, so in this case, you can see that Laravel is smart enough to figure out, alright, well if you're gonna create a table in the up method, then to undo that, you would drop the table or delete it effectively. Okay, so what does an idea consist of?

or delete it effectively. Okay, so what does an idea consist of? Well, at the moment it's very simple, right? It's just a, a string or maybe even a text column for the idea itself. So with that in mind, I could say on our table, do I want a string for the um, idea or why don't we call it from now on description. This is a description of our idea. Now, should it be a standard string

This is a description of our idea. Now, should it be a standard string or should we allow, uh, for a more verbose idea, maybe maybe more verbose. So I'm gonna use a text column instead, and that way we can fit far more than um, 255 characters. Alright? So this is looking pretty good to me. I've now defined the configuration for an ideas table. Now though, this isn't magic, it doesn't run automatically, I have to run a command to run the migrations.

Now though, this isn't magic, it doesn't run automatically, I have to run a command to run the migrations. So if I switch back to the terminal, I can say PHP Artisan Migrate. And you might say, I'm migrating my database. All right? So we give it a run, it finds this file, it runs it, it sees the schema, and it creates a new, uh, ideas table. So that will now be stored here. Okay? So if you want to visualize this, uh, I'm gonna leave this to you research some kind of database gui.

So if you want to visualize this, uh, I'm gonna leave this to you research some kind of database gui. Uh, I like to use one called Table plus. There's another tool called SQ Lights. Um, if you're on Windows, just Google it. Likely you already have something you enjoy. So I'll show you what I can do here from my terminal. I can open database slash database sq light, and this will open it up in my default, um, database gooey. All right, and here we go. So sure enough,

and this will open it up in my default, um, database gooey. All right, and here we go. So sure enough, I can see the user's table that Laravel provided for us. And I also see that new ideas table that we configured. It consists of a description and timestamps. So yeah, if you want, you can manually insert into this. You could say, um, what did we have? Build a cabin, uh, we'll leave, we can leave the timestamps know for now and then start a podcast.

Querying with DB Facade6:45

we can leave the timestamps know for now and then start a podcast. Okay? And yeah, again, notice how each idea now has an auto incrementing identifier or id. Cool. So if I wanted to read from this table, here's what we can do. Let's switch back and I will return to my routes file. And yeah, right here, rather than using the session, we're instead going to run a query against our database. And I'm gonna show you this in two steps.

we're instead going to run a query against our database. And I'm gonna show you this in two steps. First, we're gonna use a generic database query, and then second, we're gonna use something called eloquent. Okay? So we can replace this with our DB facade and we're gonna import the correct one here, illuminate Support facades db. And I'm gonna say, alright, for the ideas table, I want you to get me all of the results and this will receive ideas. So let's import this and let's do a sanity check.

to get me all of the results and this will receive ideas. So let's import this and let's do a sanity check. We're gonna run dye and dump on the ideas, and let's see if we fetched that collection. We'll come back to our editor. So if we refresh our page, we now get a Laravel collection of items. And of course, in this case, we see two items for build a cabin and start a podcast. So that means if I were to, excuse me, if I were

for build a cabin and start a podcast. So that means if I were to, excuse me, if I were to add another one, like launch a new lar cast ACAS course, if I switch back, now we're gonna have a collection of three items. Okay? So the format's a little bit different, right? We don't have an array of arrays, we have a collection of objects. So lemme show you a couple things. I can return a collection directly from my route

So lemme show you a couple things. I can return a collection directly from my route and Laravel smart enough to convert it to Jason. So if I were to come back and refresh, now we have Jason, uh, maybe I wanna grab the first item. Well, I can simply interact with it as if it were an array. So if I grab the first item, now we have build a cabin, and then if I wanna grab the description, I interact with it. Um, like any other plane object, I could say description.

description, I interact with it. Um, like any other plane object, I could say description. I come back and now we get build a cabin. And yeah, notice in every, um, scenario here, I can just return it directly from the routes and Laravel knows how to prepare the appropriate response, which is really cool. Okay, so now though, if I were to come back and refresh, this is gonna blow up because we've changed a couple things.

and refresh, this is gonna blow up because we've changed a couple things. So you'll see here we're trying to loop over just a plain array of strings, but now we have a collection of items. So let's update this. Let's go into ideas, scroll down, we can still do count. Uh, you'll see with collections, we can often interact with it as if it were a plain array. But you can also use more object oriented syntax.

with it as if it were a plain array. But you can also use more object oriented syntax. If you want like, uh, ideas count, check the count of this collection. So now if we have any, we could still use it for each. And here I will update this to the description of the idea, right? So this is now an object that is basically a representation of, uh, one, one row in our database. And that's known as active record, uh, more or less. Okay?

of, uh, one, one row in our database. And that's known as active record, uh, more or less. Okay? So if we come back, give it a refresh, sure enough, we get exactly what we had before, but now our ideas are being stored within the database. So if I were to manually add another one, start a new business or whatever you're thinking of, if I come back and refresh now that is retreat and everything's working. Very cool. Okay, so now imagine that

and refresh now that is retreat and everything's working. Very cool. Okay, so now imagine that it's six months from now and we've decided that actually for a, for an idea, we need more information. We need to store more information on the table itself, such as maybe state, what is the current state of this idea? Is it in the pending stage? Is it in progress? Is it, um, completed, right? So a simple value that indicates the current state of this idea, okay?

So a simple value that indicates the current state of this idea, okay? So you have a couple choices here. Now, again, in the past what you probably did is in your gui you just simply created a brand new, um, value here. And you can still do this, it's just, it's just not the common approach. And it, it's not overly flexible if you're working on a team with other people because they would then also need

And it, it's not overly flexible if you're working on a team with other people because they would then also need to open up their GUI and create these new records. It's not, it's not very portable in other words. So instead we have two choices. One, I'm gonna switch back, return to this migration. And if you're still in the development phase, then you could simply add your new value. In this case it would be table, string, state, uh, and then you could basically reset and rerun your migrations

In this case it would be table, string, state, uh, and then you could basically reset and rerun your migrations and that's great and that's what you should do in this exact scenario we're in. But in another situations, like I said, it's six months from now and it actually would be better to create a brand new migration. So yeah, you just have to decide where are you in the workflow here?

So yeah, you just have to decide where are you in the workflow here? Are you in a situation where it's much smarter to basically, uh, revise your original migration or should you build a brand new one? So I'm gonna show you both options. If you wanted to revise this, which is what I would do in this scenario, I would make my updates and then I would run PHB artisan migrate refresh, and you'll see what this is gonna do.

and then I would run PHB artisan migrate refresh, and you'll see what this is gonna do. It rolls back all of our migrations. So it basically undoes them, undoes them, and then it reruns them from scratch. So now keep in mind, you're gonna lose all of your data if I come back and give it a refresh. Sure enough, I can see that we now have that state column, but all of our data has been truncated. Okay? Something to be aware of.

but all of our data has been truncated. Okay? Something to be aware of. Here's the alternative option. So let's get rid of this entirely. Run it again. So now we've, we've reverted to what we originally had and yet instead, if we need to build a new migration, I would say, once again, PHB Artisan make migration. And I can run it like this by the way and it will prompt me, but you can also just depend it directly as part of the commands.

but you can also just depend it directly as part of the commands. So give it a name and often your name should just be a description of what you're doing. So I could say add state to ideas table. Alright, so let's open up my editor and we have a new migration and yeah, again, it's smart enough to figure out what the table name is.

and yeah, again, it's smart enough to figure out what the table name is. Alright, so what are we gonna do? Well, when I run this, I am going to add a new state column. And then when I undo it, and again, some people don't like to use a down method at all. They like to think forward only. So if you ever needed to undo this, you would undo it by creating a new migration that undoes it.

So if you ever needed to undo this, you would undo it by creating a new migration that undoes it. Um, but again, I'm gonna show you both options. So if I wanted to remove this column, I could say table drop column state, and that that will allow me to say migrate rollback. Alright, so we have a new migration, I can run PHP, artisan migrates. All right? It gets us up to speed and now we have our new column.

All right? It gets us up to speed and now we have our new column. And yeah, think about this. If you are working, uh, on a team, maybe you have a buddy and you're both working on this, he can pull in your changes and that includes the migration you just created. He can then run PHB Artisan migrate to instantly update his database to match what yours is. And that's the entire point and benefit of this approach. Okay? So sorry, a little bit of work there to get you up

And that's the entire point and benefit of this approach. Okay? So sorry, a little bit of work there to get you up to speed, but um, I think you'll see it's very much worth it. Okay, so let's switch back to my editor. So let's return to my routes file. And yes, so far we've learned that we can use this DB facade to perform generic queries, uh, against any table. I can get some results, I can insert, I can add a wear condition like where the ID is equal

Introducing Eloquent ORM14:32

I can get some results, I can insert, I can add a wear condition like where the ID is equal to this or where the state is equal to pending. Uh, and then get the results. Again, it's very flexible. However, we can also reach for eloquent, which is Laravel, ORM. Um, it's, it's an active record implementation that allows us to create a class that corresponds to a table and our database effectively. So that would allow us to do things like this.

and our database effectively. So that would allow us to do things like this. If I had this idea eloquent model, I could then say idea and give me all of the results. Really nice, right? Um, maybe I wanted to find the idea with an idea of one or something. I could say idea find one. And that would basically give me, um, an object oriented, uh, interface into a single row from that table, right?

And that would basically give me, um, an object oriented, uh, interface into a single row from that table, right? So let's see what we would have here. If I switch back to Table Plus and I manually created one, start a podcast and the state is pending, well, now you can see it has an idea of one. So when I perform this query idea, find one, it's going to return to me an object that uh, contains a description and contains a state.

to return to me an object that uh, contains a description and contains a state. It's incredibly readable and I think you're going to enjoy it. Okay, so let's switch back and make this a thing. So we can create an eloquent model once again through the command line like this. PHB Artisan Make a model. That's how we refer to it. What is the name of the model? Well, again, we generally want our eloquent models

What is the name of the model? Well, again, we generally want our eloquent models to be the singular form of our table name. Again, it doesn't have to be that way, but usually it is. So if our table name is ideas, then the model would be idea. If your table name is posts, then your eloquent model would be post. Okay? So should we create anything else? No, we're not there yet. So I'll skip over this. So you'll see it adds an idea model

No, we're not there yet. So I'll skip over this. So you'll see it adds an idea model to the app models directory. Let's have a look. Let's go into in our sidebar app models idea, alright? And it's very simple. We can see it extends eloquent and it's empty, but we get a lot of, uh, we get a lot of functionality even with an empty class here. So let's go back to our routes file and make use of it. I'm gonna begin by importing the idea model,

So let's go back to our routes file and make use of it. I'm gonna begin by importing the idea model, use app models idea. Next, I'm not gonna use the deep E facade here, so I can get rid of that entirely and I'm gonna replace it with what you see here. So in this case, we are finding one idea, so I could return that and it will be converted to Jason as we've learned. So if I reload the browser, sure enough, we get start a podcast and that does have an ID of one.

So if I reload the browser, sure enough, we get start a podcast and that does have an ID of one. If I instead find two, you can see how this works, right? So, uh, actually to make it crystal clear for you, if we instead pass this to die and dump, you'll see what we're actually working with is an instance of this idea model. And here are the attributes you care about. Okay? So in our case, we're fetching all ideas. We would do something like this, ideas equal idea

So in our case, we're fetching all ideas. We would do something like this, ideas equal idea and give me all of them, come back, refresh, and we see our results. This works. Okay? So next, what about this section here where we need to, uh, create a new idea? Well, we're not using the session anymore, we're gonna use our idea model idea, create, and now let's just reference all of the attributes

we're gonna use our idea model idea, create, and now let's just reference all of the attributes that the table needs, right? So in this case it would be the description of the idea and that would be idea. And then also maybe when you create an idea, the default state is always, um, pending, but now you'll see that my editor is still squawking and it's saying, hey, attribute description is guarded. So we haven't reviewed this too much yet,

and it's saying, hey, attribute description is guarded. So we haven't reviewed this too much yet, but basically, um, eloquent will guard your attributes to prevent malicious behavior. So if I click on this to go to our app model's idea class, here's what we can do for now. I'm gonna set protected guarded to an empty array, and this means eloquent. I don't actually want you to guard anything on my behalf.

and this means eloquent. I don't actually want you to guard anything on my behalf. I'm gonna take care of this and I'm gonna take care of you. I'm gonna show you what's going on here. But yeah, most of the time I think you'll find, uh, prominent developers will disable this feature entirely. We don't need eloquent protecting us here. We can be smart and thoughtful about what data we pass, um, to methods like create an update. Okay? So more on that later. Let's put a pin in it for now.

to methods like create an update. Okay? So more on that later. Let's put a pin in it for now. All right, let's switch back and you'll see the squiggly lines go away. So now when we make a post request to ideas, we fetch the user's idea and then we pass it to the create method on uh, our eloquent model. And in fact, if you want we can just end line this directly. Now, once again, no validation in place yet.

And in fact, if you want we can just end line this directly. Now, once again, no validation in place yet. We're gonna talk about that soon. But when we're done, we now have an idea model that will be returned if you need it. And then we redirect back to the homepage. So let's give this a shot. Now, let's say, um, launch a new RAAs course. Let's save it. And we now use eloquent to insert the record into the database and we see it there.

Let's save it. And we now use eloquent to insert the record into the database and we see it there. Let's have a look in table plus give this a refresh and sure enough we have our new record. And also notice when we use eloquent to insert the data, eloquent will also set the default timestamps so that we don't have to manually do that. And again, notice that state was set, it was set to pending. So yeah. Now you can imagine situations like this where maybe if state can be set to complete, there are situations

Filtering Results by State20:21

So yeah. Now you can imagine situations like this where maybe if state can be set to complete, there are situations where when you fetch all of your ideas, you only care about the ones that are not done yet. So maybe you wanna say, uh, give me all ideas where the state is set to pending, because those are the only ones that are relevant to me right now. Alright, let's do that. Come back, if we refresh currently we still get all three.

Alright, let's do that. Come back, if we refresh currently we still get all three. So now right up here, we're gonna tweak this, we're gonna add a wear condition and we're gonna say, alright, all ideas where the state is pending, give me the results. Now quick little tip here and you can't call all, I know that's a little confusing because we used it before, but as soon as you add any kind of, uh, condition as we've done here, make sure you say get.

but as soon as you add any kind of, uh, condition as we've done here, make sure you say get. So read it like this to yourself. Alright, on my ideas table, I wanna find all of them where the state column is equal to pending and then get me all of the results and store it within this variable. So now we will have a collection of ideas, but specifically only the ideas, uh, where the state is pending.

but specifically only the ideas, uh, where the state is pending. So if I come back and give this a refresh, now we only get two. And you're starting to feel the power here, right? And you're starting to see how much control you can have. For example, we could, uh, introduce query string, um, filtering like this. Let's remove this entirely. Bring it back to idea all. But we could say, well, if the user wants only pending items

Let's remove this entirely. Bring it back to idea all. But we could say, well, if the user wants only pending items and maybe that could be represented like this state equals pending, well maybe we should check for that. And if we find anything, we should filter the results for the user. Alright? These are all things you will do in real applications like this idea. And let's do this. I'm gonna start a new query and I'm gonna say I, alright, let's add a win clause

And let's do this. I'm gonna start a new query and I'm gonna say I, alright, let's add a win clause and we're gonna say, well, when we have state in the request, then I'm gonna run this function that will accept the query and the state. All right? So let's die and dump the state. And again, this is going to be equal to the value in the query string, right? It's gonna be equal to pending. Alright?

to the value in the query string, right? It's gonna be equal to pending. Alright? So, uh, we're running our query, but I immediately die and dump. So cross our fingers and we hope to see pending. And we do. If this were changed to active, now it's set to active. Alright, so now we basically have a hook. We have a hook to say, okay, well if you passed in state, then clearly you want to filter the ideas, uh, according to the states that you reference.

then clearly you want to filter the ideas, uh, according to the states that you reference. So why don't we say query where the state is equal to, uh, what is specified within the query string. And then once again, give me the results. So now we're building up a slightly more complex eloquent query, and this is gonna do the trick. So check this out if I come back and give it a refresh. Um, I don't think we have any active, uh, states, but we have some for pending and we get two

Um, I don't think we have any active, uh, states, but we have some for pending and we get two and I think we named it complete or completed. Let's see what we have complete. And now we're seeing or viewing only the completed ideas. So once again, this stuff is just wildly simple to accomplish once you learn the basic API. Alright, so clearly I am super excited just explaining this to you, but you know what, there's so much more to cover here.

to you, but you know what, there's so much more to cover here. So let's keep going in the next episode.

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